使用Apache HttpClient執(zhí)行GET、POST、PUT和DELETE請求的操作方法
Apache HttpClient 是一個功能強(qiáng)大且靈活的庫,用于在Java中處理HTTP請求。
它支持多種HTTP方法,包括GET、POST、PUT和DELETE等。
本教程將演示如何使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE請求。
Maven依賴
要使用Apache HttpClient,您需要在pom.xml文件中添加以下依賴項(xiàng):
<!-- 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請求,并打印響應(yīng)。
JSONPlaceholder API
為了演示目的,我們將使用JSONPlaceholder API,該API提供了一個虛擬的在線RESTful端點(diǎn),用于測試和原型設(shè)計。
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響應(yīng)狀態(tài)
System.out.println("Response Code: " + response.getCode());
// 獲取HTTP響應(yīng)內(nèi)容
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);
// 設(shè)置JSON負(fù)載
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
request.setEntity(entity);
// 設(shè)置頭部
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// 執(zhí)行請求
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 獲取HTTP響應(yīng)狀態(tài)
System.out.println("Response Code: " + response.getCode());
// 獲取HTTP響應(yīng)內(nèi)容
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);
// 設(shè)置JSON負(fù)載
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
request.setEntity(entity);
// 設(shè)置頭部
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// 執(zhí)行請求
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 獲取HTTP響應(yīng)狀態(tài)
System.out.println("Response Code: " + response.getCode());
// 獲取HTTP響應(yīng)內(nèi)容
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響應(yīng)狀態(tài)
System.out.println("Response Code: " + response.getCode());
// 獲取HTTP響應(yīng)內(nèi)容
String content = EntityUtils.toString(response.getEntity());
System.out.println("Response Content: \n" + content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}示例輸出
Response Code: 200
Response Content:
{}
額外配置
- 設(shè)置自定義頭部:可以通過調(diào)用請求對象(如HttpGet、HttpPost、HttpPut、HttpDelete)上的
setHeader方法來設(shè)置自定義頭部。 - 處理重定向:默認(rèn)情況下,Apache HttpClient會自動處理重定向。您可以使用自定義的
HttpClientBuilder來自定義這種行為。 - 設(shè)置超時:可以使用
RequestConfig來設(shè)置連接和套接字超時。
結(jié)論
使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE HTTP請求非常方便。
通過遵循本教程,您現(xiàn)在應(yīng)該能夠創(chuàng)建并執(zhí)行這些類型的請求,處理響應(yīng),并定制HTTP請求和響應(yīng)過程。
Apache HttpClient提供了一整套功能,使其成為處理Java應(yīng)用程序中HTTP操作的優(yōu)秀選擇。
JSONPlaceholder API作為一個實(shí)用且方便的來源,適合用來測試和原型化您的HTTP請求。
到此這篇關(guān)于如何使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE請求的文章就介紹到這了,更多相關(guān)Apache HttpClient執(zhí)行GET、POST、PUT和DELETE請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談生產(chǎn)者消費(fèi)者模型(Linux系統(tǒng)下的兩種實(shí)現(xiàn)方法)
下面小編就為大家?guī)硪黄獪\談生產(chǎn)者消費(fèi)者模型(Linux系統(tǒng)下的兩種實(shí)現(xiàn)方法)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
centos 6.8命令行下使用pptpsetup進(jìn)行pptp撥號的實(shí)現(xiàn)方法
centos 6.8 命令行下可使用pptpsetup進(jìn)行pptp撥號,首先安裝ppp,pptp和pptp-setup三個包,使用pptpsetup進(jìn)行連接,下面給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2016-10-10
crontab定時任務(wù)不執(zhí)行的一些原因總結(jié)
這篇文章主要給大家總結(jié)介紹了關(guān)于crontab定時任務(wù)不執(zhí)行的一些原因,對每種可能發(fā)生的原因都給出了解決方法,對遇到這個問題的朋友們具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
linux下使用cmake編譯安裝mysql的詳細(xì)教程
這篇文章主要介紹了linux下使用cmake編譯安裝mysql的詳細(xì)教程,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10
CentOS7環(huán)境下gcc(版本10.2.0)升級詳細(xì)過程
大家好,本篇文章主要講的是CentOS7環(huán)境下gcc(版本10.2.0)升級詳細(xì)過程,感興趣的同學(xué)快來看一看吧,希望對你有幫助2021-11-11
CentOS7 + node.js + nginx + MySQL搭建服務(wù)器全過程
這篇文章主要介紹了關(guān)于CentOS7 + node.js + nginx + MySQL搭建服務(wù)器的全過程,文章通過一步步的步驟進(jìn)行介紹的很詳細(xì),相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03

