1. HttpClient 簡介
HttpClient 是Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。
2. Java 中使用方法
2.1 創建實例
官方推薦方法是創建 CloseableHttpClient 類
CloseableHttpClient httpclient = HttpClients.createDefault();
2.2 創建請求實例
// 創建 GET 請求實例
HttpGet httpGet = new HttpGet("http://127.0.0.1/test");
// 創建 POST 請求實例
HttpPost httpPost = new HttpPost("http://127.0.0.1/test2");
2.3 添加請求頭
httpPost.addHeader("Content-Type", "application/form-data");
2.4 設置配置
httpPost.setConfig(RequestConfig.custom().setConnectTimeout(100).build());
2.5 添加實體
2.5.1 傳遞 Json 類型的字符串
httpPost.setEntity(new StringEntity("{\"name\":\"Martin\"}", "UTF-8"));
2.5.2 傳遞 form 表單
使用 BasicNameValuePair 封裝 key - value,並添加到 List 集合中
List<BasicNameValuePair> basicNameValuePairs =new ArrayList<>();
basicNameValuePairs.add(new BasicNameValuePair("name", "Martin"));
basicNameValuePairs.add(new BasicNameValuePair("age", "10"));
basicNameValuePairs.add(new BasicNameValuePair("sex", "male"));
httpPost.setEntity(new UrlEncodedFormEntity(basicNameValuePairs, "UTF-8"));
2.5.3 傳遞 Multipart/form-data 類型的數據
// 創建 MultipartEntityBuilder
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
// 設置字符編碼
ContentType contentType=ContentType.create("text/plain", Charset.forName("UTF-8"));
// 添加文本內容
entityBuilder.addPart("id", new StringBody("value",contentType));
// 添加文件
// 以二進制的形式添加數據,可以添加File、InputStream、byte[]類型的數據。
entityBuilder.addBinaryBody("fileName1", new File("test.txt"));
// 以Key/Value的形式添加ContentBody類型的數據
entityBuilder.addPart("fileName2", new FileBody(new File("test.txt")));
// 設置實體
httpPost.setEntity(entityBuilder.build());
2.6 發送請求
// 發送請求
HttpResponse httpResponse = httpclient.execute(httpPost);
2.7 釋放連接
finally {
httpPost.releaseConnection();
}
站在前人的肩膀上前行,感謝以下博客及文獻的支持。