使用Apache HttpClient執(zhí)行GET、POST、PUT和DELETE請(qǐng)求的操作方法
Apache HttpClient 是一個(gè)功能強(qiáng)大且靈活的庫,用于在Java中處理HTTP請(qǐng)求。
它支持多種HTTP方法,包括GET、POST、PUT和DELETE等。
本教程將演示如何使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE請(qǐng)求。
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>
示例場(chǎng)景
我們將創(chuàng)建簡(jiǎn)單的Java類,這些類將向指定的URL發(fā)送GET、POST、PUT和DELETE請(qǐng)求,并打印響應(yīng)。
JSONPlaceholder API
為了演示目的,我們將使用JSONPlaceholder API,該API提供了一個(gè)虛擬的在線RESTful端點(diǎn),用于測(cè)試和原型設(shè)計(jì)。
GET請(qǐng)求
發(fā)送GET請(qǐng)求的Java類
創(chuàng)建一個(gè)名為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請(qǐng)求 HttpGet request = new HttpGet(url); // 執(zhí)行請(qǐng)求 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請(qǐng)求
發(fā)送POST請(qǐng)求的Java類
創(chuàng)建一個(gè)名為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請(qǐng)求 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í)行請(qǐng)求 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請(qǐng)求
發(fā)送PUT請(qǐng)求的Java類
創(chuàng)建一個(gè)名為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請(qǐng)求 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í)行請(qǐng)求 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請(qǐng)求
發(fā)送DELETE請(qǐng)求的Java類
創(chuàng)建一個(gè)名為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請(qǐng)求 HttpDelete request = new HttpDelete(url); // 執(zhí)行請(qǐng)求 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)用請(qǐng)求對(duì)象(如HttpGet、HttpPost、HttpPut、HttpDelete)上的
setHeader
方法來設(shè)置自定義頭部。 - 處理重定向:默認(rèn)情況下,Apache HttpClient會(huì)自動(dòng)處理重定向。您可以使用自定義的
HttpClientBuilder
來自定義這種行為。 - 設(shè)置超時(shí):可以使用
RequestConfig
來設(shè)置連接和套接字超時(shí)。
結(jié)論
使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE HTTP請(qǐng)求非常方便。
通過遵循本教程,您現(xiàn)在應(yīng)該能夠創(chuàng)建并執(zhí)行這些類型的請(qǐng)求,處理響應(yīng),并定制HTTP請(qǐng)求和響應(yīng)過程。
Apache HttpClient提供了一整套功能,使其成為處理Java應(yīng)用程序中HTTP操作的優(yōu)秀選擇。
JSONPlaceholder API作為一個(gè)實(shí)用且方便的來源,適合用來測(cè)試和原型化您的HTTP請(qǐng)求。
到此這篇關(guān)于如何使用Apache HttpClient來執(zhí)行GET、POST、PUT和DELETE請(qǐng)求的文章就介紹到這了,更多相關(guān)Apache HttpClient執(zhí)行GET、POST、PUT和DELETE請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(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)方法)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01centos 6.8命令行下使用pptpsetup進(jìn)行pptp撥號(hào)的實(shí)現(xiàn)方法
centos 6.8 命令行下可使用pptpsetup進(jìn)行pptp撥號(hào),首先安裝ppp,pptp和pptp-setup三個(gè)包,使用pptpsetup進(jìn)行連接,下面給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2016-10-10crontab定時(shí)任務(wù)不執(zhí)行的一些原因總結(jié)
這篇文章主要給大家總結(jié)介紹了關(guān)于crontab定時(shí)任務(wù)不執(zhí)行的一些原因,對(duì)每種可能發(fā)生的原因都給出了解決方法,對(duì)遇到這個(gè)問題的朋友們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01linux下使用cmake編譯安裝mysql的詳細(xì)教程
這篇文章主要介紹了linux下使用cmake編譯安裝mysql的詳細(xì)教程,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10CentOS7環(huán)境下gcc(版本10.2.0)升級(jí)詳細(xì)過程
大家好,本篇文章主要講的是CentOS7環(huán)境下gcc(版本10.2.0)升級(jí)詳細(xì)過程,感興趣的同學(xué)快來看一看吧,希望對(duì)你有幫助2021-11-11CentOS7 + node.js + nginx + MySQL搭建服務(wù)器全過程
這篇文章主要介紹了關(guān)于CentOS7 + node.js + nginx + MySQL搭建服務(wù)器的全過程,文章通過一步步的步驟進(jìn)行介紹的很詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。2017-03-03