您的位置:首页 > 理论基础 > 计算机网络

HttpClient—Apache的HTTP 协议工具包

2017-01-14 19:31 309 查看

介绍

androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。

区别

HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,

HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。

使用方法:

Get请求方式

String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do";
public HttpClientServer(){

}
public String doGet(String username,String password){
String url= urlAddress + "?username="+username+"&password="+password;
// 使用get方法连接服务器
HttpGet httpGet = new HttpGet(url)..getParams().getParameter("true");

HttpClient hc = new DefaultHttpClient();  //创建HttpClient的对象
try {
// 客户端开始向指定的网址发送请求
HttpResponse ht = hc.execute(httpGet);  //获得HttpResponse

if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity he = ht.getEntity();    //获取实体
InputStream is = he.getContent();  //获取一个输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while((readLine =br.readLine()) != null){
response = response + readLine;
}
is.close();
br.close();
return response;
}else{
return "error";
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
}


Post的请求方式

public String doPost(String username,String password){
HttpPost httpPost = new HttpPost(urlAddress);
List params = new ArrayList();  //创建集合,放入数据
NameValuePair pair1 = new BasicNameValuePair("username", username);
NameValuePair pair2 = new BasicNameValuePair("password", password);
params.add(pair1);
params.add(pair2);

HttpEntity he;
try {
he = new UrlEncodedFormEntity(params, "gbk");
httpPost.setEntity(he);

} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

HttpClient hc = new DefaultHttpClient();
try {
HttpResponse ht = hc.execute(httpPost);
//连接成功
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity het = ht.getEntity();
InputStream is = het.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while((readLine =br.readLine()) != null){
response = response + readLine;
}
is.close();
br.close();
return response;
}else{
return "error";
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息