Android学习——Apache HTTP Client
作者:互联网
Apache HTTP Client
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包。
HttpClient下载地址。在Android中已经集成了HttpClient。
GET请求
http地址
String path="http://10.0.2.2:8080/Android_NetServer/LoginServlet?username=root$password=123456";
HTTPGet连接对象
HttpGet get=new HttpGet(path);
取得HttpClient对象
HttpClient httpClient=new DefaultHttpClient();
向服务器发送请求,并返回相应对象
HttpResponse response=httpClient.execute(get);
获取响应的状态码,取得返回的字符串
int status=response.getStatusLine().getStatusCode();
switch (status){
case HttpStatus.SC_OK:
//200
HttpEntity entity=response.getEntity();
//取得返回的字符串
String result=EntityUtils.toString(entity,"utf-8");
System.out.println(result);
break;
case HttpStatus.SC_NOT_FOUND:
//404
break;
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
//500
break;
}
POST请求
使用post方法进行参数传递时,需要使用NameValuePair来保存要传递的参数。另外,还需要设置所使用的字符集。
使用apache HttpClient的POST请求
private void postRequest(){
new Thread(new Runnable() {
@Override
public void run() {
String path="http://10.0.2.2:8080/Android_NetServer/LoginServlet";
//创建请求对象
HttpPost post=new HttpPost();
//传递参数
ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username","vince"));
params.add(new BasicNameValuePair("password","123"));
try {
HttpEntity entity = new UrlEncodedFormEntity(params);
post.setEntity(entity);
HttpClient httpClient=new DefaultHttpClient();
HttpResponse response=httpClient.execute(post);
switch (response.getStatusLine().getStatusCode()){
case HttpStatus.SC_OK:
//200
String result=EntityUtils.toString(response.getEntity());
System.out.println(result);
break;
case HttpStatus.SC_NOT_FOUND:
//404
Log.i("HttpClient","404");
break;
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
//500
Log.i("HttpClient","500");
break;
}
}catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
小结
两种请求方式的区别:
get:大小不能超过4KB,速度快,会在URL上显示,不安全。
post:大小不限制,速度比get慢,不会在URL上显示,安全性高。
标签:case,HttpStatus,break,SC,Client,Apache,new,Android,HttpClient 来源: https://blog.csdn.net/UUUUUltraman/article/details/89328549