Http Client 的用法
上次介紹了 Java
中使用 HttpUrlConnection
調用 web
接口。這次帶來更方便的一種方式
本文只介紹 Http Client
庫的一般用法。詳細的使用可以查看官方文檔,英文不好的同學可以查看翻譯版。
官方文檔:https://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html
翻譯版:https://blog.csdn.net/zhongzh86/article/details/84070561
ok,下面直接進入正題
使用前需要先引入依賴如下:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
準備用於測試的兩個 web
接口:
@RestController
@RequestMapping("/demo")
public class HttpDemoController {
@RequestMapping(path = "sentGet", method = RequestMethod.GET)
public String getMethod(HttpServletRequest request){
System.out.println("method: " + request.getMethod());
System.out.println("content type: " + request.getContentType());
Map<String, String[]> parameterMap = request.getParameterMap();
System.out.println("parameters:------------------- ");
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()){
System.out.println(entry.getKey() + "->" + entry.getValue()[0]);
}
System.out.println("------------------------------ ");
return "GET 返回的數據";
}
@RequestMapping(path = "sentPost", method = RequestMethod.POST)
public String postMethod(HttpServletRequest request) throws Exception{
System.out.println("method: " + request.getMethod());
System.out.println("content type: " + request.getContentType());
Map<String, String[]> parameterMap = request.getParameterMap();
System.out.println("parameters:------------------- ");
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()){
System.out.println(entry.getKey() + "->" + entry.getValue()[0]);
}
System.out.println("------------------------------ ");
// 得到body的內容
String s = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
System.out.println("body: " + s);
return "POST 返回的數據";
}
}
使用 Http Client
的步驟:
- 創建
HttpClient
對象 - 確定
URL
和參數 - 創建方法類型對象
- 設置
body
內容(GET可以不用) - 獲取結果
- 關閉資源
POST
的方式的具體代碼如下:
public static final String POST_URL = "http://127.0.0.1:8080/demo/sentPost";
public static void doPost() throws Exception{
// 1.創建HttpClient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2. 確定URL和參數,這裏設置的參數會被拼接到url後面
URI uri = new URIBuilder(POST_URL)
.addParameter("HeaderKey", "headerValue")
.build();
// 3.創建方法類型對象,也可以使用GetMethod對象(老版本)
HttpPost httpPost = new HttpPost(uri);
// 4.設置body參數,GET方式省略這一步
// text/plain表示純文本
HttpEntity httpEntity = new StringEntity("body content",
ContentType.create("text/plain", "UTF-8"));
// 表單,會被處理後拼接到url中
/*List<NameValuePair> forms = new ArrayList<>();
forms.add(new BasicNameValuePair("userName","mkii"));
forms.add(new BasicNameValuePair("password","1234"));
HttpEntity httpEntity = new UrlEncodedFormEntity(forms, "UTF-8");*/
httpPost.setEntity(httpEntity);
// 5.獲取結果
CloseableHttpResponse response = httpClient.execute(httpPost);
// 得到response header
Header[] allHeaders = response.getAllHeaders();
// 協議狀態碼等信息
StatusLine statusLine = response.getStatusLine();
// 返回body
String s = EntityUtils.toString(response.getEntity());
System.out.println(s);
// 6.關閉資源
response.close();
httpClient.close();
}