使用Apache HttpClient執(zhí)行GET、POST、PUT和DELETE請求的操作方法
Apache HttpClient 是一個功能強大且靈活的庫,用于在Java中處理HTTP請求。
它支持多種HTTP方法,包括GET、POST、PUT和DELETE等。
本教程將演示如何使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE請求。
Maven依賴
要使用Apache HttpClient,您需要在pom.xml文件中添加以下依賴項:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.3</version>
</dependency>示例場景
我們將創(chuàng)建簡單的Java類,這些類將向指定的URL發(fā)送GET、POST、PUT和DELETE請求,并打印響應。
JSONPlaceholder API
為了演示目的,我們將使用JSONPlaceholder API,該API提供了一個虛擬的在線RESTful端點,用于測試和原型設計。
GET請求
發(fā)送GET請求的Java類
創(chuàng)建一個名為HttpClientGetExample的類,代碼如下:
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class HttpClientGetExample {
public static void main(String[] args) {
String url = "https://jsonplaceholder.typicode.com/posts/1";
// 創(chuàng)建HttpClient
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 創(chuàng)建HttpGet請求
HttpGet request = new HttpGet(url);
// 執(zhí)行請求
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 獲取HTTP響應狀態(tài)
System.out.println("Response Code: " + response.getCode());
// 獲取HTTP響應內容
String content = EntityUtils.toString(response.getEntity());
System.out.println("Response Content: \n" + content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}示例輸出
Response Code: 200
Response Content:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
POST請求
發(fā)送POST請求的Java類
創(chuàng)建一個名為HttpClientPostExample的類,代碼如下:
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class HttpClientPostExample {
public static void main(String[] args) {
String url = "https://jsonplaceholder.typicode.com/posts";
String json = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
// 創(chuàng)建HttpClient
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 創(chuàng)建HttpPost請求
HttpPost request = new HttpPost(url);
// 設置JSON負載
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
request.setEntity(entity);
// 設置頭部
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// 執(zhí)行請求
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 獲取HTTP響應狀態(tài)
System.out.println("Response Code: " + response.getCode());
// 獲取HTTP響應內容
String content = EntityUtils.toString(response.getEntity());
System.out.println("Response Content: \n" + content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}示例輸出
Response Code: 201
Response Content:
{
"title": "foo",
"body": "bar",
"userId": 1,
"id": 101
}
PUT請求
發(fā)送PUT請求的Java類
創(chuàng)建一個名為HttpClientPutExample的類,代碼如下:
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class HttpClientPutExample {
public static void main(String[] args) {
String url = "https://jsonplaceholder.typicode.com/posts/1";
String json = "{\"id\":1,\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
// 創(chuàng)建HttpClient
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 創(chuàng)建HttpPut請求
HttpPut request = new HttpPut(url);
// 設置JSON負載
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
request.setEntity(entity);
// 設置頭部
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// 執(zhí)行請求
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 獲取HTTP響應狀態(tài)
System.out.println("Response Code: " + response.getCode());
// 獲取HTTP響應內容
String content = EntityUtils.toString(response.getEntity());
System.out.println("Response Content: \n" + content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}示例輸出
Response Code: 200
Response Content:
{
"id": 1,
"title": "foo",
"body": "bar",
"userId": 1
}
DELETE請求
發(fā)送DELETE請求的Java類
創(chuàng)建一個名為HttpClientDeleteExample的類,代碼如下:
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class HttpClientDeleteExample {
public static void main(String[] args) {
String url = "https://jsonplaceholder.typicode.com/posts/1";
// 創(chuàng)建HttpClient
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 創(chuàng)建HttpDelete請求
HttpDelete request = new HttpDelete(url);
// 執(zhí)行請求
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 獲取HTTP響應狀態(tài)
System.out.println("Response Code: " + response.getCode());
// 獲取HTTP響應內容
String content = EntityUtils.toString(response.getEntity());
System.out.println("Response Content: \n" + content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}示例輸出
Response Code: 200
Response Content:
{}
額外配置
- 設置自定義頭部:可以通過調用請求對象(如HttpGet、HttpPost、HttpPut、HttpDelete)上的
setHeader方法來設置自定義頭部。 - 處理重定向:默認情況下,Apache HttpClient會自動處理重定向。您可以使用自定義的
HttpClientBuilder來自定義這種行為。 - 設置超時:可以使用
RequestConfig來設置連接和套接字超時。
結論
使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE HTTP請求非常方便。
通過遵循本教程,您現(xiàn)在應該能夠創(chuàng)建并執(zhí)行這些類型的請求,處理響應,并定制HTTP請求和響應過程。
Apache HttpClient提供了一整套功能,使其成為處理Java應用程序中HTTP操作的優(yōu)秀選擇。
JSONPlaceholder API作為一個實用且方便的來源,適合用來測試和原型化您的HTTP請求。
到此這篇關于如何使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE請求的文章就介紹到這了,更多相關Apache HttpClient執(zhí)行GET、POST、PUT和DELETE請求內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Ubuntu系統(tǒng)缺少iptables工具的解決方法
文章介紹了如何解決Docker啟動失敗的問題,主要原因是系統(tǒng)缺少iptables工具,解決方案包括在Ubuntu/Debian系統(tǒng)上安裝iptables并重啟Docker服務,此外,還詳細描述了如何在離線環(huán)境下安裝iptables,需要的朋友可以參考下2026-02-02
Linux搭建NFS服務器實現(xiàn)Linux文件共享
本文詳細介紹了在Linux環(huán)境下搭建NFS(Network File System)服務器的過程,包括安裝配置、權限設置、安全加固、客戶端掛載、性能優(yōu)化及故障排查等內容,需要的朋友可以參考下2026-04-04

