java中HttpClient使用方法舉例詳解
概要
Java 11引入了HttpClient作為一個新的API,用于在Java應(yīng)用程序中進(jìn)行HTTP通信。HttpClient提供了發(fā)送HTTP請求和接收HTTP響應(yīng)的功能,并且相比于依賴第三方庫如Apache HttpClient或OkHttp,它提供了一種簡單、一致且更加集成的方式來處理HTTP通信。作為Java的一部分,HttpClient被設(shè)計(jì)成與Java平臺更好地集成,使得開發(fā)者能夠更輕松地處理HTTP請求和響應(yīng),同時減少了對外部庫的依賴。
HttpClient 的主要類包括:java.net.http.HttpClient:HttpClient是用于發(fā)送HTTP請求和處理HTTP響應(yīng)的主要類。它提供了一種簡單且一致的方式來執(zhí)行HTTP操作,包括同步和異步的請求發(fā)送、連接池管理、請求和響應(yīng)的攔截器等功能。
java.net.http.HttpRequest:HttpRequest是用于表示HTTP請求的類。通過HttpRequest對象,您可以設(shè)置請求的URL、請求方法、請求頭、請求體等信息,并構(gòu)建一個完整的HTTP請求對象,用于發(fā)送給服務(wù)器。
java.net.http.HttpResponse:HttpResponse是用于表示HTTP響應(yīng)的類。當(dāng)客戶端發(fā)送HTTP請求后,服務(wù)器會返回一個HTTP響應(yīng),HttpResponse對象用于表示這個響應(yīng)。通過HttpResponse對象,您可以獲取響應(yīng)的狀態(tài)碼、響應(yīng)頭、響應(yīng)體等信息,以便進(jìn)一步處理響應(yīng)。
但是,如果你在使用Java 11之前的版本,并且想要使用類似的功能,你可能需要引入第三方庫的依賴,如Apache HttpClient。以下是使用Apache HttpClient的一個示例依賴項(xiàng):
<!-- Apache HttpClient依賴 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
JDK11 及之后的版本 舉例
第一種以下是一個簡單的例子,演示如何使用HttpClient發(fā)送GET請求:
public static void main(String[] args) throws Exception {
// 創(chuàng)建一個HttpClient實(shí)例
HttpClient httpClient = HttpClient.newHttpClient();
// 創(chuàng)建一個HTTP請求 指定URI
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create("https://api.uomg.com/api/rand.qinghua")) // 使用 URI 創(chuàng)建請求
.build();
// 發(fā)送 HTTP 請求并獲取響應(yīng)
HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
// 輸出響應(yīng)的狀態(tài)碼和響應(yīng)體
System.out.println("響應(yīng)狀態(tài)碼:" + response.statusCode());
System.out.println("響應(yīng)體:" + response.body());
}
第二種以下是一個示例,演示如何使用sendAsync()方法發(fā)送異步GET請求:
public static void main(String[] args) {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create("https://api.uomg.com/api/rand.qinghua"))
.build();
CompletableFuture<HttpResponse<String>> future = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());
future.thenAccept(response -> {
System.out.println("響應(yīng)狀態(tài)碼:" + response.statusCode());
System.out.println("響應(yīng)體:" + response.body());
}).join();// 等待異步操作完成
}
第三種:
以下是一個使用HttpClient發(fā)送POST請求的示例代碼:
public static void main(String[] args) throws Exception {
// 創(chuàng)建一個 HttpClient 實(shí)例
HttpClient client = HttpClient.newHttpClient();
// 構(gòu)建請求體參數(shù)
Map<String, String> requestBody = new HashMap<>();
requestBody.put("param1", "value1");
requestBody.put("param2", "value2");
// 構(gòu)建 POST 請求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.uomg.com/api/rand.qinghua"))
.header("Content-Type", "application/json") // 設(shè)置請求頭
.POST(buildRequestBody(requestBody)) // 設(shè)置請求體
.build();
// 發(fā)送請求并獲取響應(yīng)
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// 輸出響應(yīng)碼和響應(yīng)體
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
}
// 構(gòu)建請求體
// buildRequestBody方法的作用是將一個Map<String, String>類型的數(shù)據(jù)轉(zhuǎn)換為符合JSON格式的字符串
// 轉(zhuǎn)換后:{"param1":"value1","param2":"value2"}
private static HttpRequest.BodyPublisher buildRequestBody(Map<String, String> data) {
StringBuilder builder = new StringBuilder();
builder.append("{");
for (Map.Entry<String, String> entry : data.entrySet()) {
builder.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\",");
}
builder.deleteCharAt(builder.length() - 1); // 刪除最后一個逗號
builder.append("}");
return HttpRequest.BodyPublishers.ofString(builder.toString());
}JDK11 之前的版本 舉例
第一步引入依賴:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
第二步封裝一個工具類:
public class HttpClientUtil {
static final int TIMEOUT_MSEC = 5 * 1000;
/**
* 發(fā)送GET方式請求
*/
public static String doGet(String url, Map<String, String> paramMap) {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if (paramMap != null) {
for (String key : paramMap.keySet()) {
builder.addParameter(key, paramMap.get(key));
}
}
URI uri = builder.build();
//創(chuàng)建GET請求
HttpGet httpGet = new HttpGet(uri);
//發(fā)送請求
response = httpClient.execute(httpGet);
//判斷響應(yīng)狀態(tài)
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 發(fā)送POST方式請求,參數(shù)為鍵值對形式
*/
public static String doPost(String url, Map<String, String> paramMap) throws IOException {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請求
HttpPost httpPost = new HttpPost(url);
// 創(chuàng)建參數(shù)列表
if (paramMap != null) {
List<NameValuePair> paramList = new ArrayList();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
// 模擬表單
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 設(shè)置請求配置
httpPost.setConfig(builderRequestConfig());
// 執(zhí)行http請求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 發(fā)送POST方式請求,參數(shù)為JSON格式
*/
public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請求
HttpPost httpPost = new HttpPost(url);
if (paramMap != null) {
//構(gòu)造json格式數(shù)據(jù)
JSONObject jsonObject = new JSONObject();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
jsonObject.put(param.getKey(), param.getValue());
}
StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
//設(shè)置請求編碼
entity.setContentEncoding("utf-8");
//設(shè)置數(shù)據(jù)類型
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
// 設(shè)置請求配置
httpPost.setConfig(builderRequestConfig());
// 執(zhí)行http請求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 構(gòu)建請求配置
*/
private static RequestConfig builderRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(TIMEOUT_MSEC) // 設(shè)置連接超時時間
.setConnectionRequestTimeout(TIMEOUT_MSEC) // 設(shè)置從連接池獲取連接的超時時間
.setSocketTimeout(TIMEOUT_MSEC) // 設(shè)置請求獲取數(shù)據(jù)的超時時間
.build();
}
}第三步使用這個工具類:(簡單例子測試一下)
public static void main(String[] args) {
String s = HttpClientUtil.doGet("https://api.uomg.com/api/rand.qinghua", null);
System.out.println(s);
}
使用JDK11添加如下依賴
<!--JDK11缺少的依賴-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
小結(jié)
總的來說,HttpClient是一個功能強(qiáng)大、靈活易用的HTTP客戶端庫,適用于各種Java應(yīng)用程序,如Web應(yīng)用、后臺服務(wù)等,能夠幫助開發(fā)者輕松實(shí)現(xiàn)HTTP通信功能。
到此這篇關(guān)于java中HttpClient使用方法的文章就介紹到這了,更多相關(guān)java中HttpClient使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot項(xiàng)目上高并發(fā)問題的解決方案
本章演示在springboot項(xiàng)目中的高并發(fā)demo,演示導(dǎo)致的問題,以及單機(jī)部署下的解決方案和集群部署下的解決方式以及分布式下的解決方案,文中通過圖文結(jié)合的方式講解的非常詳細(xì),需要的朋友可以參考下2024-06-06
java 算法之希爾排序詳解及實(shí)現(xiàn)代碼
這篇文章主要介紹了java 算法之希爾排序詳解及實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-03-03
SpringBoot Redisson 集成的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot Redisson 集成的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05

