有的時候,我們的 Spring Boot 應用需要調用第三方接口,這個接口可能是 Http協議、可能是 WebService、可能是 FTP或其他格式,本章討論 Http 接口的調用。
通常基於 Http/Https 協議的接口請求動作 POST/GET/PUT/DELETE/PATCH 操作。交互的內容可以是文本、Json 或 Xml。
在 Spring Boot 中使用 Apache HttpClient 類庫能夠方便快捷地解決 Http 調用問題。
1 新建 Spring Boot Maven 示例工程項目
注意:是用來 IDEA 開發工具
- File > New > Project,如下圖選擇
Spring Initializr
然后點擊 【Next】下一步 - 填寫
GroupId
(包名)、Artifact
(項目名) 即可。點擊 下一步
groupId=com.fishpro
artifactId=httpclient - 選擇依賴
Spring Web Starter
前面打鈎。 - 項目名設置為
spring-boot-study-httpclient
.
2 引入依賴 Pom
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3 編寫 HttpClient 代碼示例
3.1 傳統的 get/post
大多數情況,第三方提供的接口都是基於 GET/POST,而且一般需要設定 url、http head 的值,所以我們下面的代碼是針對只有 GET/POST 的接口設定
/**
* 傳統的 http get/post 實現
* */
public class HttpClientUtils {
/**
* http get
* @param url 可帶參數的 url 鏈接
* @param heads http 頭信息
* */
public String get(String url,Map<String,String> heads){
org.apache.http.client.HttpClient httpClient= HttpClients.createDefault();
HttpResponse httpResponse = null;
String result="";
HttpGet httpGet=new HttpGet(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpGet.addHeader(s,heads.get(s));
}
}
try{
httpResponse=httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
if(httpEntity!=null){
result= EntityUtils.toString(httpEntity,"utf-8");
}
}catch (IOException e){
e.printStackTrace();
}
return result;
}
/**
* http post
* */
public static String post(String url, String data, Map<String, String> heads){
org.apache.http.client.HttpClient httpClient= HttpClients.createDefault();
HttpResponse httpResponse = null;
String result="";
HttpPost httpPost=new HttpPost(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpPost.addHeader(s,heads.get(s));
}
}
try{
StringEntity s=new StringEntity(data,"utf-8");
httpPost.setEntity(s);
httpResponse=httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
if(httpEntity!=null){
result= EntityUtils.toString(httpEntity,"utf-8");
}
}catch (IOException e){
e.printStackTrace();
}
return result;
}
}
調用也非常簡單
3.2 基於 REST 接口的操作方法
我們可以單獨為 REST 風格接口提供方法,因為 HttpClient 為我們單獨提供了針對 GET/POST/PUT/DELETE 的方法。
3.2.1 GET 方法
- 首先創建一個http請求 HttpGet httpGet=new HttpGet(url);
- 自定義一個 Response Handler
- 執行 httpclient.execute(請求,Handler)
- 處理返回
/**
* http get
* @param url 可帶參數的 url 鏈接
* @param heads http 頭信息
* */
public static String get(String url,Map<String,String> heads){
org.apache.http.client.HttpClient httpClient= HttpClients.createDefault();
HttpResponse httpResponse = null;
String result="";
HttpGet httpGet=new HttpGet(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpGet.addHeader(s,heads.get(s));
}
}
try{
httpResponse=httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
if(httpEntity!=null){
result= EntityUtils.toString(httpEntity,"utf-8");
}
}catch (IOException e){
e.printStackTrace();
}
return result;
}
3.2.2 POST 方法
- 首先創建一個http請求 HttpPost httpPost = new HttpPost(url);
- 自定義一個 Response Handler,向POST中添加數據(JSON 信息)和 Header信息
httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json");
- 執行 httpclient.execute(請求,Handler)
- 處理返回
/**
* post 方法
* @param url post 的 url
* @param data 數據 application/json 的時候 為json格式
* @param heads Http Head 參數
* */
public static String post(String url,String data,Map<String,String> heads) throws IOException{
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpPost.addHeader(s,heads.get(s));
}
}
StringEntity stringEntity = new StringEntity(data);
httpPost.setEntity(stringEntity);
System.out.println("Executing request " + httpPost.getRequestLine());
// Create a custom response handler
ResponseHandler < String > responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
return responseBody;
}
}
3.2.3 PUT 方法
- 首先創建一個http請求 HttpPut httpPut = new HttpPut(url);
- 自定義一個 Response Handler,向POST中添加數據(JSON 信息)和 Header信息
httpPut.setHeader("Accept", "application/json"); httpPut.setHeader("Content-type", "application/json");
- 執行 httpclient.execute(請求,Handler)
- 處理返回
/**
* put 方法
* @param url put 的 url
* @param data 數據 application/json 的時候 為json格式
* @param heads Http Head 參數
* */
public static String put(String url,String data,Map<String,String> heads) throws IOException{
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpPut.addHeader(s,heads.get(s));
}
}
StringEntity stringEntity = new StringEntity(data);
httpPut.setEntity(stringEntity);
System.out.println("Executing request " + httpPut.getRequestLine());
// Create a custom response handler
ResponseHandler < String > responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPut, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
return responseBody;
}
}
3.2.4 DELETE 方法
- 首先創建一個http請求 HttpDelete httpDelete = new HttpDelete(url);
- 自定義一個 Response Handler
- 執行 httpclient.execute(請求,Handler)
- 處理返回
/**
* delete 方法
* @param url delete 的 url
* @param heads Http Head 參數
* */
public static String delete(String url,Map<String,String> heads) throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpDelete httpDelete = new HttpDelete(url);
if(heads!=null){
Set<String> keySet=heads.keySet();
for(String s:keySet){
httpDelete.addHeader(s,heads.get(s));
}
}
System.out.println("Executing request " + httpDelete.getRequestLine());
// Create a custom response handler
ResponseHandler < String > responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpDelete, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
return responseBody;
}
}
參考鏈接
https://www.javaguides.net/2018/10/apache-httpclient-get-post-put-and-delete-methods-example.html