一、HttpClient类的介绍
HttpClient是Apache下的一个Java开源项目,其作用是提供了一个高效、灵活、可扩展的处理HTTP请求的Java工具包,是用于Android上进行网络通信的标准工具。 使用HttpClient可以很方便地在Android应用程序中执行HTTP请求,例如GET、POST等请求,获取服务器发送的响应和状态信息。
二、HttpClient请求流程
HttpClient请求的流程主要分为以下几个步骤:
- 创建 HttpClient 实例
HttpClient httpClient = new DefaultHttpClient();
- 创建 HttpGet 或 HttpPost 请求对象
HttpGet httpGet = new HttpGet(url); HttpPost httpPost = new HttpPost(url);
- 设置请求参数
List<NameValuePair> paramList = new ArrayList<>(); paramList.add(new BasicNameValuePair("username", "test")); paramList.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8"); httpPost.setEntity(entity);
- 客户端执行请求操作,并接收服务端返回的响应结果
HttpResponse httpResponse = httpClient.execute(httpGet);
三、HttpClient基本请求
1、GET请求
GET请求通过在URL后添加参数来传递参数信息。下面是一个使用HttpClient发送GET请求的例子。
public static String sendHttpGetRequest(String url) {
String response = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
response = EntityUtils.toString(entity, "UTF-8");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
2、POST请求
POST请求通过在请求体中添加参数来传递参数信息。下面是一个使用HttpClient发送POST请求的例子。
public static String sendHttpPostRequest(String url, Map<String, String> params) {
String response = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> paramList = new ArrayList<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
response = EntityUtils.toString(httpEntity, "UTF-8");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
四、HttpClient高级请求
1、HttpClient连接池
默认情况下,每次HttpClient请求操作都会创建一个新的HttpClient实例,如果在同一个应用程序中进行多次请求,这样就会导致资源的浪费。因此,在实际开发中可以考虑使用HttpClient连接池来维护一组可用的HttpClient实例,减少资源的浪费。
public class HttpClientPool {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 5000;
static {
connMgr = new PoolingHttpClientConnectionManager();
connMgr.setMaxTotal(200);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
requestConfig = RequestConfig.custom()
.setSocketTimeout(MAX_TIMEOUT)
.setConnectTimeout(MAX_TIMEOUT)
.setConnectionRequestTimeout(MAX_TIMEOUT)
.build();
}
public static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connMgr)
.setDefaultRequestConfig(requestConfig)
.build();
return httpClient;
}
}
2、HttpClient拦截器
HttpClient拦截器是一个在请求执行前后对请求进行处理的机制。 拦截器可以在请求执行前添加一些公共属性,比如请求头、cookies等。也可以在请求执行成功后对返回的响应结果进行加工处理。
public class HttpHeaderInterceptor implements HttpRequestInterceptor {
private Map<String, String> header;
public HttpHeaderInterceptor(Map<String, String> header) {
this.header = header;
}
@Override
public void process(HttpRequest request, HttpContext context) {
for (Map.Entry<String, String> entry : header.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
}
3、HttpClient文件上传
HttpClient可以通过MultipartEntity来进行文件上传操作。
public static String uploadFile(String url, Map<String, String> params, File file) {
String response = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.TEXT_PLAIN));
}
builder.addPart("filename", new FileBody(file));
httpPost.setEntity(builder.build());
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}