java使用httpclient 發(fā)送請(qǐng)求的示例
HttpClient 是Apache Jakarta Common 下的子項(xiàng)目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。
一、使用的Jar包
首先需要在maven中引入如下包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.18</version> </dependency>
二、接口代碼
Get的無參/有參請(qǐng)求
/**
* @param url 接口地址
* @param headers 請(qǐng)求頭
* @Description get請(qǐng)求
*/
public static String getData(String url, Map<String, String> headers) {
String StringResult = "";
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
if (headers != null && !headers.isEmpty()) {
for (String head : headers.keySet()) {
httpGet.addHeader(head, headers.get(head));
}
}
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8).trim();
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
StringResult = "errorException:" + e.getMessage();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return StringResult;
}請(qǐng)求實(shí)列:在這里無參請(qǐng)求就不展示,可自行試驗(yàn)
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
String data = getData("https://api.vvhan.com/api/covid?city=重慶", headers);
System.out.println(data);請(qǐng)求結(jié)果:
{
"success": true,
"data": {
"updatetime": "2022-12-23 09:46:10",
"country": "中國",
"province": "重慶",
"city": "重慶",
"now": {
"sure_new_loc": "未公布",
"sure_new_hid": "未公布",
"sure_present": 3108
},
"history": {
"sure_cnt": 10452,
"cure_cnt": 7337,
"die_cnt": 7
},
"danger": {
"high_risk": 0,
"medium_risk": 0
}
}
}
Post請(qǐng)求(application/x-www-form-urlencoded)
/**
* @param url 接口地址
* @param list NameValuePair(簡(jiǎn)單名稱值對(duì)節(jié)點(diǎn)類型)類似html中的input
* @param headers 請(qǐng)求頭(默認(rèn)Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
* @Description post請(qǐng)求
*/
public static String postData(String url, ArrayList<NameValuePair> list, Map<String, String> headers) {
String StringResult = "";
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (list != null && !list.isEmpty()) {
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
httpPost.setEntity(formEntity);
}
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
if (headers != null && !headers.isEmpty()) {
for (String head : headers.keySet()) {
httpPost.addHeader(head, headers.get(head));
}
}
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
} catch (Exception e) {
StringResult = "errorException:" + e.getMessage();
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return StringResult;
}請(qǐng)求實(shí)列:
ArrayList<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username", "用戶名"));
list.add(new BasicNameValuePair("password", "1234"));
String s = postData("http://127.0.0.1:3000/aaa/file/testPost.jsp", list, null);
System.out.println(s);請(qǐng)求結(jié)果:
用戶名
1234
application/x-www-form-urlencoded; charset=UTF-8
Post請(qǐng)求(application/json)
/**
* @param url 接口地址
* @param jsonString json字符串
* @param headers 請(qǐng)求頭(默認(rèn)Content-Type:application/json; charset=UTF-8)
* @Description post Json 請(qǐng)求
*/
public static String postJsonData(String url, @NotNull String jsonString, Map<String, String> headers) {
String StringResult = "";
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity jsonEntity = new StringEntity(jsonString, Consts.UTF_8);
jsonEntity.setContentEncoding(Consts.UTF_8.name());
httpPost.setEntity(jsonEntity);
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
if (headers != null && !headers.isEmpty()) {
for (String head : headers.keySet()) {
httpPost.addHeader(head, headers.get(head));
}
}
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
} catch (Exception e) {
StringResult = "errorException:" + e.getMessage();
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return StringResult;
}請(qǐng)求實(shí)列:
JSONObject jsonObject = new JSONObject();
jsonObject.put("demo", "456789");
jsonObject.put("demo1", "哈哈哈愛發(fā)火");
String s = postJsonData("http://127.0.0.1:3000/api/workflow/v1/insert2", jsonObject.toJSONString(), null);
System.out.println(s);請(qǐng)求結(jié)果:

Get請(qǐng)求url拼接
/**
* @param url 接口地址(無參數(shù)/有參)
* @param params 拼接參數(shù)集合
* @Description get請(qǐng)求URL拼接參數(shù) & URL編碼
*/
public static String getAppendUrl(String url, Map<String, String> params) {
StringBuffer buffer = new StringBuffer(url);
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
if (buffer.indexOf("?") >= 0) {
buffer.append("&");
} else {
buffer.append("?");
}
String value = "";
try {
value = URLEncoder.encode(params.get(key), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buffer.append(key)
.append("=")
.append(value);
}
}
return buffer.toString();
}
請(qǐng)求實(shí)列:
Map<String, String> params = new HashMap<>();
params.put("city", "重慶");
params.put("number", "手機(jī)號(hào)");
String appendUrl = getAppendUrl("https://TestGetSplice/index", params);
String appendUrl1 = getAppendUrl("https://TestGetSplice/index?a=33", params);
System.out.println(appendUrl);
System.out.println(appendUrl1);請(qǐng)求結(jié)果:
https://TestGetSplice/index?number=%E6%89%8B%E6%9C%BA%E5%8F%B7&city=%E9%87%8D%E5%BA%86
https://TestGetSplice/index?a=33&number=%E6%89%8B%E6%9C%BA%E5%8F%B7&city=%E9%87%8D%E5%BA%86
三、使用的類
import com.alibaba.fastjson.JSONObject; import com.sun.istack.internal.NotNull; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; 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.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
四、標(biāo)準(zhǔn)字符集的常量定義
這些字符集保證在Java平臺(tái)的每個(gè)實(shí)現(xiàn)上都可用。
import java.nio.charset.StandardCharsets; StandardCharsets.UTF_8
五、請(qǐng)求狀態(tài)常量
import org.apache.http.HttpStatus; // 200 HttpStatus.SC_OK
到此這篇關(guān)于java使用httpclient 發(fā)送請(qǐng)求的文章就介紹到這了,更多相關(guān)httpclient 發(fā)送請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- java?11新特性HttpClient主要組件及發(fā)送請(qǐng)求示例詳解
- Java通過HttpClient進(jìn)行HTTP請(qǐng)求的代碼詳解
- java中httpclient封裝post請(qǐng)求和get的請(qǐng)求實(shí)例
- Java commons-httpclient如果實(shí)現(xiàn)get及post請(qǐng)求
- JAVA通過HttpClient發(fā)送HTTP請(qǐng)求的方法示例
- Java使用HttpClient實(shí)現(xiàn)Post請(qǐng)求實(shí)例
- java實(shí)現(xiàn)HttpClient異步請(qǐng)求資源的方法
- Java高并發(fā)場(chǎng)景下的 HttpClient請(qǐng)求優(yōu)化實(shí)現(xiàn)
相關(guān)文章
Java自定義類數(shù)組報(bào)null的相關(guān)問題及解決
這篇文章主要介紹了Java自定義類數(shù)組報(bào)null的相關(guān)問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
聊聊springboot靜態(tài)資源加載的規(guī)則
這篇文章主要介紹了springboot靜態(tài)資源加載的規(guī)則,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
springboot的java配置方式(實(shí)例講解)
下面小編就為大家分享一篇實(shí)例講解springboot的java配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-11-11
盤點(diǎn)總結(jié)SpringBoot自帶工具類使用提升開發(fā)效率
這篇文章主要為大家介紹了盤點(diǎn)總結(jié)SpringBoot自帶工具類使用提升開發(fā)效率,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
分布式調(diào)度XXL-Job整合Springboot2.X實(shí)戰(zhàn)操作過程(推薦)
這篇文章主要介紹了分布式調(diào)度XXL-Job整合Springboot2.X實(shí)戰(zhàn)操作,包括定時(shí)任務(wù)的使用場(chǎng)景和常見的定時(shí)任務(wù),通過本文學(xué)習(xí)幫助大家該選擇哪個(gè)分布式任務(wù)調(diào)度平臺(tái),對(duì)此文感興趣的朋友一起看看吧2022-04-04
Java實(shí)現(xiàn)DBF文件讀寫操作的完整指南
DBF是一種數(shù)據(jù)庫文件格式,主要存儲(chǔ)結(jié)構(gòu)化數(shù)據(jù),本文將詳細(xì)介紹如何在Java中使用JDBF庫來讀取和創(chuàng)建DBF文件,有需要的小伙伴可以參考一下2025-04-04
jpa?onetomany?使用級(jí)連表刪除被維護(hù)表數(shù)據(jù)時(shí)的坑
這篇文章主要介紹了jpa?onetomany?使用級(jí)連表刪除被維護(hù)表數(shù)據(jù)時(shí)的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12

