首页 > 移动平台 > 详细

Android HttpClient

时间:2015-04-02 21:00:26      阅读:231      评论:0      收藏:0      [点我收藏+]

    使用Apache提供的HttpClient接口进行HTTP操作。

    GET方法:

// http地址 
String httpUrl = ;
//HttpGet连接对象 
HttpGet httpRequest = new HttpGet(httpUrl);
//取得HttpClient对象 
HttpClient httpclient = new DefaultHttpClient();
//请求HttpClient,取得HttpResponse 
HttpResponse httpResponse = httpclient.execute(httpRequest);
//请求成功 
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取得返回的字符串 
String strResult = EntityUtils.toString(httpResponse.getEntity());
System.out.println(strResult); 
}else{
System.out.println("请求错误!");
}

    POST方法:

// http地址 
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
//HttpPost连接对象 
HttpPost httpRequest = new HttpPost(httpUrl);
//使用NameValuePair来保存要传递的Post参数 
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加要传递的参数 
params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
//设置字符集 
HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
//请求httpRequest 
httpRequest.setEntity(httpentity);
//取得默认的HttpClient 
HttpClient httpclient = new DefaultHttpClient();
//取得HttpResponse 
HttpResponse httpResponse = httpclient.execute(httpRequest);
//HttpStatus.SC_OK表示连接成功 
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取得返回的字符串 
String strResult = EntityUtils.toString(httpResponse.getEntity());
System.out.println(strResult); 
}else{
System.out.println("请求错误!");
}

Android HttpClient

原文:http://my.oschina.net/u/593225/blog/395374

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!