Android中的HttpClient是一种用于发送和接收HTTP请求的开源库,可以让Android开发者更加方便地实现HTTP请求。HttpClient可以支持很多HTTP功能,包括GET/POST请求、GZip压缩、文件上传、客户端身份验证等。
HttpClient的使用方法
需要在Android项目中导入HttpClient的依赖库,在build.gradle文件中添加:
compile 'org.apache.httpcomponents:httpclient:4.5.2'
需要创建HttpClient对象,使用HttpClientBuilder类:
HttpClient httpClient = HttpClientBuilder.create().build();
可以使用HttpClient对象来发送HTTP请求,比如GET请求:
HttpGet httpGet = new HttpGet("http://www.example.com"); HttpResponse response = httpClient.execute(httpGet);
可以使用HttpResponse对象来获取HTTP响应:
int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity());
HttpClient还支持POST请求、GZip压缩、文件上传、客户端身份验证等功能,使用方法如下:
- POST请求:
HttpPost httpPost = new HttpPost("http://www.example.com"); List
params = new ArrayList (); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = httpClient.execute(httpPost); - GZip压缩:
httpGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = httpClient.execute(httpGet); InputStream is = response.getEntity().getContent(); GZIPInputStream gzipIs = new GZIPInputStream(is);
- 文件上传:
HttpPost httpPost = new HttpPost("http://www.example.com"); File file = new File("/path/to/file"); FileBody fileBody = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", fileBody); httpPost.setEntity(builder.build()); HttpResponse response = httpClient.execute(httpPost);
- 客户端身份验证:
HttpGet httpGet = new HttpGet("http://www.example.com"); String authString = "username:password"; String encodedAuthString = Base64.encodeBase64String(authString.getBytes()); httpGet.addHeader("Authorization", "Basic " + encodedAuthString); HttpResponse response = httpClient.execute(httpGet);