在Android开发中咱们常常会用到网络链接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便咱们使用各类Http服务。你能够把HttpClient想象成一个浏览器,经过它的API咱们能够很方便的发出GET,POST请求(它的功能远不止这些,这里只介绍如何使用HttpClient发起GET或者POST请求)php
GET 方式浏览器
//先将参数放入List,再对参数进行URL编码
List params = new LinkedList();
params.add(new BasicNameValuePair("param1", "中国"));
params.add(new BasicNameValuePair("param2", "value2"));
//对参数编码
String param = URLEncodedUtils.format(params, "UTF-8");
//baseUrl
String baseUrl = "http://ubs.free4lab.com/php/method.php";
//将URL与参数拼接
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);服务器
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //发起GET请求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//获取服务器响应内容
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}网络
POST方式post
//和GET方式同样,先将参数放入List
params = new LinkedList();
params.add(new BasicNameValuePair("param1", "Post方法"));
params.add(new BasicNameValuePair("param2", "第二个参数"));编码
try {
HttpPost postMethod = new HttpPost(baseUrl);
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中code
HttpResponse response = httpClient.execute(postMethod); //执行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容orm
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}utf-8