Android基础知识之网络通信

  • 1、HTTP通信方式
  • 1.1、HttpClient接口 - get 方式:
  • 1.2、HttpClient接口 - post 方式:
  • 1.3、get/post请求的区别:


1、HTTP通信方式

1.1、HttpClient接口 - get 方式:

// 用 HttpClient发送请求,分为五步
// 第一步:创建HttpClient对象
HttpClient httpClient = new DeafaultHttpClient();
String url = "http://192.168.1.112:8080/test.jsp?name="+name+"&password=" = pwd;
// 第二步:创建代表请求的对象,参数是访问的服务器地址
HttpGet httpGet = new HttpGet(url);
try{
	// 第三步:执行请求,获取服务器发还的相应对象
	HttpResponse response = httpClient.execute(httpGet);
	// 第四步:检查相应的状态是否正常,检查状态码的值是200表示正常
	if (response.getStatusLine().getStatusCode() == 200){
		// 第五步:从相应对象当中取出数据,放到entity当中
		HttpEntity entity = response.getEntity();
		BufferedReader reader = new BufferedReader(
			new InputStreamReader(entity.getContent()));
		String result = reader.readerLine();
		Log.d("HTTP","GET:"+result);
	}
}catch(Exception e){
	e.printStackTrace();
}

1.2、HttpClient接口 - post 方式:

// 用 HttpClient发送请求,分为五步
// 第一步:创建HttpClient对象
HttpClient httpClient = new DeafaultHttpClient();
String url = "http://192.168.1.112:8080/test.jsp";
// 第二步:生成使用Post方法的请求对象
HttpPost httpPost = new HttpPost(url);
// NameValuepair对象代表了一个需要发往服务器的键值对
NameValuePair pair1 = new BasicNameValuePair("name",name);
NameValuePair pair2 = new BasicNameValuePair("password",pwd);
// 将准备好的键值对放置在一个List中
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(pair1);
pairs.add(pair2);
try{
	// 创建代表请求体的对象(注意,是请求体)
	HttpEntity requestEntity = new UrlEncodedFormEntity(pairs);
	// 将请求体放置在请求对象当中
	httpPost.setEntity(requestEntity);
	// 执行请求对象
	try{
		// 第三步:执行请求对象,获取服务器发还的相应对象
		HttpResponse response = httpClient.execute(httpPost);
		// 第四步:检查相应的状态是否正常:检查状态码的值是200表示正常
		if (response.getStatusLine().getStatusCode() == 200){
			// 第五步:从相应对象当中取出数据,放到entity当中
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(
				new InputStreamReader(entity.getContent()));
			String result = reader.readerLine();
			Log.d("HTTP","POST:"+result);
		}
	}catch(Exception e){
	e.printStackTrace();
	}
}catch(Exception e){
	e.printStackTrace();
}

1.3、get/post请求的区别:

  • Get请求方式:
    显式请求方式,请求参数会在URL上显示,相对快,安全性较低,请求数据的大小一般不超过1kb。
  • Post请求方式:
    隐式请求方式,请求参数将会在http请求的实体内容中进行传输,相对慢,安全性较高 ,请求数据的大小没有限制

注:GET请求方式和POST请求区别在于请求参数在传递的过程中方式不同。

  • 当Android客户端访问https网站,默认情况下,受证书信任限制,无法访问,可以有两种解决方法来实现:
    1、客户端添加指定信任证书
    2、客户端信任所有https,免证书验证
  • 信任特定证书

android 通信系统的log android网络通信_java

android 通信系统的log android网络通信_android_02

  • 信任所有证书

android 通信系统的log android网络通信_http_03

android 通信系统的log android网络通信_android_04

android 通信系统的log android网络通信_https_05