这是mars老师的课程,让我们来学习android应用程序中有关http的操作,我把它搬到博客上来,大家一起交流学习
为什么http协议叫做超文本传输协议, 因为http协议不仅仅能传输文本, 还能传输图片, 音频, 视频等等.
http协议是应用层通信协议.
报文即数据两种发送带参数的http请求:
1. 用Get方式发送http请求.
private String baseUrl = "http://192.168.1.100:8081/serverside/name";
public void onClick(View v) {
String url = baseUrl + "?" + "name=" + "zhangsan" + "&age=" + "20";
//参数是键值对, 键值对用&进行连接.
// url地址是: http://192.168.1.100:8081/serverside/name?name=zhangsan&age=20
private HttpResponse httpResponse = null;
//生成一个请求对象
HttpGet httpGet = new HttpGet(url);
//生成一个Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
InputStream inputStream = null;
try {
//使用Http客户端发送请求对象
httpResponse = httpClient.execute(httpGet);
//从http响应对象中得到http entity
httpEntity = httpResponse.getEntity();
//从http entity对象中得到内容,以输入输出流的形式
inputStream = httpEntity.getContent();
//读取流的操作
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
//把http的响应内容打印出来
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
finally{
try{
//关闭输入流
inputStream.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
2. 用Post方式发送http请求.
public void onClick(View v) {
// NameValuePair对象代表一个键值对
NameValuePair nameValuePair1 = new BasicNameValuePair("name","zhangsan");
NameValuePair nameValuePair2 = new BasicNameValuePair("age","20");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//把要发送的键值对参数放到一个list中去
nameValuePairs.add(nameValuePair1);
nameValuePairs.add(nameValuePair2);
try {
HttpEntity requestHttpEntity = new UrlEncodeFormEntiry(nameValuePairs);
//把参数数据封装在http entity中
HttpPost httpPost = new HttpPost(baseUrl);
//生成一个httpPost对象
httpPost.setEntity(requestHttpEntity);
//为http post请求设置http entity
HttpClient httpClient = new DefaultHttpClient();
InputStream inputStream = null;
httpResponse = httpClient.execute(httpPost);
//下面的代码和使用http get方式相同
httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
inputStream.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
两种方法的主要区别是如何携带参数(也就是键值对)的问题,get方法是把要传递的参数直接封装在url中(get方法中的url=要访问的服务器网址信息+需要传递的参数),而post方法是把传递的参数封装在一个list 对象里,然后把这个装有键值对的对象直接绑在httpPost对象上,不是放在url中。