一、HttpClient類的介紹
HttpClient是Apache下的一個Java開源項目,其作用是提供了一個高效、靈活、可擴展的處理HTTP請求的Java工具包,是用於Android上進行網絡通信的標準工具。
使用HttpClient可以很方便地在Android應用程序中執行HTTP請求,例如GET、POST等請求,獲取服務器發送的響應和狀態信息。
二、HttpClient請求流程
HttpClient請求的流程主要分為以下幾個步驟:
- 創建 HttpClient 實例
- 創建 HttpGet 或 HttpPost 請求對象
- 設置請求參數
- 客戶端執行請求操作,並接收服務端返回的響應結果
HttpClient httpClient = new DefaultHttpClient();
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請求
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連接池
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;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/238571.html
微信掃一掃
支付寶掃一掃