以登陆系统为例:

一、创建服务端程序

1、打开VS2012,新建项目,创建ASP.NET WEB应用程序 ,命名为MyApp

2、添加新建项,选择一般处理程序,创建Login.ashx

C# Code:  Login.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace MyApp.Remote
{
/// <summary>
/// Login 的摘要说明
/// </summary>
public class Login : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
switch (context.Request["type"])
{
case "login":
loginValidate(context);
break;
default:
break
;
}

} /// <summary>
/// 验证登陆
/// </summary>
/// <param name="context"></param>
private void loginValidate(HttpContext context)
{
string account = context.Request["Account"].ToString();
string password = context.Request["Password"].ToString();
if (account == "" && password == "")
{
string realName="HelloWord";
context.Response.Write("{\"Result\":\"1\",\"RealName\":\""+realName+"\"}");
//实际输出:{"Result":"1","RealName":"HelloWord"}
//注意:双引号需要用转义符\
}
else
{
context.Response.Write("{\"Result\":\"0\"}");
} }
public bool IsReusable
{
get
{
return false;
}
}
}
}

3、到这里就完成服务端的验证代码登陆了。

浏览器输入地址访问:http://localhost:11946/Remote/Login.ashx?type=login&Account=123&Password=123

4、这时候程序还没有部署到IIS,那么如何在VS调试的时候,客户端可以通过IP访问该程序?

客户端通过IP和端口访问服务端程序

二、创建客户端程序

1、界面布局 layout \ activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp"
android:orientation="vertical" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" > <TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="账号" /> <EditText
android:id="@+id/edittext_loginAccount"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="number" > <requestFocus />
</EditText>
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" > <TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="密码" /> <EditText
android:id="@+id/editetext_loginPassword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPassword" />
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" > <CheckBox
android:id="@+id/checkbox_remindPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码" />
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" > <Button
android:id="@+id/button_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录" />
</LinearLayout> </LinearLayout>

2、Java Code : MainActivity.java

package com.example.net;

import java.io.BufferedReader;
import java.io.InputStreamReader; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject; import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity { private String ServerUrl = "http://192.168.137.210:11946/Remote/";
private EditText et_loginAccount;
private EditText et_loginPassword;
private CheckBox cb_remindPassword;
private Button btn_login;
private ProgressDialog progressDialog; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new
StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); et_loginAccount = (EditText) findViewById(R.id.edittext_loginAccount);
et_loginPassword = (EditText) findViewById(R.id.editetext_loginPassword);
cb_remindPassword = (CheckBox) findViewById(R.id.checkbox_remindPassword);
btn_login = (Button) findViewById(R.id.button_login); btn_login.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// loading 对话框
progressDialog = ProgressDialog.show(MainActivity.this, "", "服务器连接中...", true, false);
// 开启线程去验证登录
new Thread() {
@Override
public void run() {
// 向handler发消息
mHandler.sendEmptyMessage(0
);
}
}.start();

}
}); } private Handler mHandler = new Handler() { @Override
public void handleMessage(Message msg) {
// 登录验证
loginValidate();
} }; private void loginValidate() {
// 打开网络连接
HttpClient client = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
// 服务器提交地址
String url = ServerUrl + "Login.ashx?type=login&Account=" + et_loginAccount.getText().toString() + "&Password=" + et_loginPassword.getText().toString();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// 填充数据流
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
builder.append(s);
}
// 读取Json返回数组
JSONObject jsonObject = new JSONObject(builder.toString());
String re_result = jsonObject.getString("Result");
String re_realName = jsonObject.getString("RealName");
if (re_result.equals("1")) {
Toast.makeText(MainActivity.this, "验证成功!" + re_realName, Toast.LENGTH_SHORT).show();
// TODO:跳转页面
} else {
Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "服务器数据读取失败", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
} }

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

少了上面两句代码会报错android.os.NetworkOnMainThreadException即,在主线程访问网络时出的异常

Android在4.0之前的版本支持在主线程中访问网络,但是在4.0以后对这部分程序进行了优化,也就是说访问网络的代码不能写在主线程中了。

稍后研究多线程

3、别放了加上权限 AndroidManifest.xml

  <!-- sd卡读取权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- 访问网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- 完全退出程序权限 -->
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />

【Android-网络通讯】 客户端与.Net服务端Http通讯的更多相关文章

  1. android客户端app和服务端交互token的作用

    Android客户端和服务端如何使用Token和Session niceheart关注1人评论34644人阅读2014-09-16 16:38:44   对于初学者来说,对Token和Session的 ...

  2. 网络版shell之网络编程练习篇--telnet服务端

    网络版shell之网络编程练习篇--telnet服务端   以前写过一个shell命令解释器,对与shell命令解释器的执行流程有了清晰的认识,这段时间学习网络编程,至于网络编程的细节以及知识点,已经 ...

  3. C#使用Thrift简介,C#客户端和Java服务端相互交互

    C#使用Thrift简介,C#客户端和Java服务端相互交互 本文主要介绍两部分内容: C#中使用Thrift简介 用Java创建一个服务端,用C#创建一个客户端通过thrift与其交互. 用纯C#实 ...

  4. 利用python多线程实现多个客户端与单个服务端的远程ssh

    本次实验设计两个方面的代码,第一个是客户端,代码如下: import os from socket import * c = socket(AF_INET,SOCK_STREAM) c.connect ...

  5. 6-1 建立客户端与zk服务端的连接

    6-1 建立客户端与zk服务端的连接 zookeeper原生java api使用 会话连接与恢复; 节点的增删改查; watch与acl的相关操作; 导入jar包;

  6. Linux下更改oracle客户端字符集和服务端字符集

    from:http://blog.csdn.net/chid/article/details/6166506 Linux 下更改 oracle 客户端字符集和服务端字符集 1.Linux 下更改 or ...

  7. XFire客户端调用CXF服务端(四)

    前面章节:http://www.cnblogs.com/xiehongwei/p/8082337.html 已经开发出了CXF服务端,现在用XFire开发客户端调用CXF服务端,代码如下: impor ...

  8. java版gRPC实战之六:客户端动态获取服务端地址

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  9. 关于kafka客户端版本与服务端版本不一致导致的一次坑

    上周开发了一个功能,需要使用kafka接上游数据并入库,本地开发时,自己安装了一个kafka服务,开发测试时使用本地的kafka服务给主题发消息,然后在自己本地的代码中进行调试.使用的kafka版本如 ...

随机推荐

  1. orcale数据库授权码

    Product Code:4t46t6vydkvsxekkvf3fjnpzy5wbuhphqzserial Number:601769password:xs374ca

  2. mysql 查询最佳实践

    (1)负向条件查询不能使用索引 select * from order where status!=0 and stauts!=1 not in/not exists都不是好习惯 (2)前导模糊查询不 ...

  3. dfs/bfs专项训练

    A.棋盘问题——poj1321 在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别.要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放 ...

  4. 小木棒HDU1455(DFS+剪枝)

    题意:HDU1455 给出n个小木棒的长度,他们是又数根长度相同的木棒剪短得来的,问没剪短之前的木棒长度最短是多少. 思路: 见代码:https://www.cnblogs.com/fqfzs/p/9 ...

  5. 作为小白该如何抉择python编辑器?

    刚开始接触编程,有一个好的编辑器上手,那学习起来肯定是事半功倍的!本篇就给大家介绍适合零基础小白学习Python的四种编辑器,希望大家受用! 1.Sublime Text: 这是一个轻量级的代码编辑器 ...

  6. RabbitMQ快速开始

    ①:安装rabbitmq所需要的依赖包 yum install build-essential openssl openssl-devel unixODBC unixODBC-devel make g ...

  7. Python 变量作用域与函数

    Python 的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言的一种继承.Py ...

  8. QAbstractItemModel使用样例与解析(Model::index使用了createIndex,它会被销毁吗?被销毁了,因为栈对象出了括号就会被销毁)

    参考:qt源码 qstandarditemmodel_p.h qstandarditemmodel.h qstandarditemmodel.cpp qabstractitemmodel.h qabs ...

  9. 前端工程师应该知道的yarn知识

    yarn 是在工作中离不开的工具,但在工作中,很多人基本只会使用 yarn install,而且会手动删除 node-modules,或删除 yarn.lock 文件等不规范操作.本文将从一些基础的知 ...

  10. Java并发与多线程教程(3)

    Java中的锁 锁像synchronized同步块一样,是一种线程同步机制,但比Java中的synchronized同步块更复杂.因为锁(以及其它更高级的线程同步机制)是由synchronized同步 ...