文章目錄
一、簡介
1、HttpClient
HttpClient 是Apache HttpComponents 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。HTTP 協議可能是現在 Internet 上使用得最多、最重要的協議了,越來越多的 Java 應用程序需要直接通過 HTTP 協議來訪問網絡資源。雖然在 JDK 的 java net包中已經提供了訪問 HTTP 協議的基本功能,但是對於大部分應用程序來說,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 是Apache HttpComponents 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。
2、HTTP協議的特點如下
- 支持客戶/服務器模式。
- 簡單快速:客戶向服務器請求服務時,只需傳送請求方法和路徑。請求方法常用的有GET、HEAD、POST。每種方法規定了客戶與服務器聯系的類型不同。 由於HTTP協議簡單,使得HTTP服務器的程序規模小,因而通信速度很快。
- 靈活:HTTP允許傳輸任意類型的數據對象。正在傳輸的類型由Content-Type加以標記。
- 無連接:無連接的含義是限制每次連接只處理一個請求。服務器處理完客戶的請求,並收到客戶的應答后,即斷開連接。采用這種方式可以節省傳輸時間。
- 無狀態:HTTP協議是無狀態協議。無狀態是指協議對於事務處理沒有記憶能力。缺少狀態意味着如果后續處理需要前面的信息,則它必須重傳,這樣可能導致每次連接傳送的數據量增大。另一方面,在服務器不需要先前信息時它的應答就較快。
3、使用HttpClient發送請求、接收響應很簡單,一般需要如下幾步即可
- 創建HttpClient對象。
- 創建請求方式的實例。創建請求方法的實例,並指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。
- 添加請求參數。如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對於HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。
- 發送Http請求。調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse。
- 獲取返回的內容。調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容。
- 釋放資源。無論執行方法是否成功,都必須釋放資源;
二、spring boot集成HttpClient
1、pom.xml添加httpclient的jar包依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
2、測試類
import com.lydms.utils.HttpClientUtils;
import java.io.IOException;
import java.util.HashMap;
public class test {
public static void main(String[] args) {
test test = new test();
//測試get請求
test.testGet();
//測試String類型Post請求
test.testStringPost();
//測試Map類型Post請求
test.testMapPost();
}
/** * 測試POST請求(String入參) */
private void testStringPost() {
String url = "http://107.12.57.187:8080/sms/post1";
String str = "{\"english\":\"json\"}";
try {
String result = HttpClientUtils.post(url, str);
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
/** * 測試POST請求(Map入參) */
private void testMapPost() {
String url = "http://107.12.57.187:8080/sms/post1";
HashMap<String, String> map = new HashMap<>();
map.put("english", "json");
try {
String result = HttpClientUtils.post(url, map);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
/** * 測試GET請求 */
private void testGet() {
String url = "http://107.12.57.187:8080/sms/get";
try {
String result = HttpClientUtils.get(url);
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、工具類
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
public class HttpClientUtils {
private static final Logger logger = LogManager.getLogger(HttpClientUtils.class);
/** * 封裝POST請求(Map入參) * * @param url 請求的路徑 * @param map 請求的參數 * @return * @throws IOException */
public static String post(String url, Map map) throws IOException {
// 1、創建HttpClient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2、創建請求方式的實例
HttpPost httpPost = new HttpPost();
try {
httpPost.setURI(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
// 3、添加請求參數(設置請求和傳輸超時時間)
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpPost.setConfig(requestConfig);
ArrayList<NameValuePair> list = new ArrayList<>();
Set<Map.Entry> entrySet = map.entrySet();
for (Map.Entry entry : entrySet) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
list.add(new BasicNameValuePair(key, value));
}
httpPost.setEntity(new UrlEncodedFormEntity(list, org.apache.http.protocol.HTTP.UTF_8));
// 4、發送Http請求
HttpResponse response = httpClient.execute(httpPost);
// 5、獲取返回的內容
String result = null;
int statusCode = response.getStatusLine().getStatusCode();
if (200 == statusCode) {
result = EntityUtils.toString(response.getEntity());
} else {
logger.info("請求第三方接口出現錯誤,狀態碼為:{}", statusCode);
return null;
}
// 6、釋放資源
httpPost.abort();
httpClient.getConnectionManager().shutdown();
return result;
}
/** * 封裝POST請求(String入參) * * @param url 請求的路徑 * @param data String類型數據 * @return * @throws IOException */
public static String post(String url, String data) throws IOException {
// 1、創建HttpClient對象
HttpClient httpClient = HttpClientBuilder.create().build();
// 2、創建請求方式的實例
HttpPost httpPost = new HttpPost(url);
// 3、添加請求參數(設置請求和傳輸超時時間)
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
// 設置請求參數
httpPost.setEntity(new StringEntity(data, "UTF-8"));
// 4、發送Http請求
HttpResponse response = httpClient.execute(httpPost);
// 5、獲取返回的內容
String result = null;
int statusCode = response.getStatusLine().getStatusCode();
if (200 == statusCode) {
result = EntityUtils.toString(response.getEntity());
} else {
logger.info("請求第三方接口出現錯誤,狀態碼為:{}", statusCode);
return null;
}
// 6、釋放資源
httpPost.abort();
httpClient.getConnectionManager().shutdown();
return result;
}
/** * 封裝GET請求 * * @param url * @return * @throws IOException */
public static String get(String url) throws IOException {
// 1、創建HttpClient對象
HttpClient httpClient = HttpClientBuilder.create().build();
// 2、創建請求方式的實例
HttpGet httpGet = new HttpGet(url);
// 3、添加請求參數(設置請求和傳輸超時時間)
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpGet.setConfig(requestConfig);
// 4、發送Http請求
HttpResponse response = httpClient.execute(httpGet);
// 5、獲取返回的內容
String result = null;
int statusCode = response.getStatusLine().getStatusCode();
if (200 == statusCode) {
result = EntityUtils.toString(response.getEntity());
} else {
logger.info("請求第三方接口出現錯誤,狀態碼為:{}", statusCode);
return null;
}
// 6、釋放資源
httpGet.abort();
httpClient.getConnectionManager().shutdown();
return result;
}
}
