Android网络请求基础概述
本文将直接演示具体用法,先掌握如何调用,再理解背后的原理。
一、HttpPost请求
具体代码实现如下:
try {
// 建立网络连接
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// 配置参数,模拟HTML表单的提交方式
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList = new ArrayList<NameValuePair>();();BasicNameValuePair param = new BasicNameValuePair("param1", paramValue);
paramList.add(param);
post.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF-8));
// 发送HttpPost请求,并接收返回的HttpResponse对象
HttpResponse httpResponse = httpClient.execute(post);
// 检查请求的响应状态码,若为200则表示服务器已成功处理客户端请求
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 提取返回的数据内容
String result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {}
二、HttpGet请求
代码如下:
try {
HttpClient httpClient = new DefaultHttpClient();
// 模仿地址栏直接在链接后附加参数,例如:http://127.0.0.1:8080/test/test.php?name=;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {}