java使用httpclient 發(fā)送請求的示例
HttpClient 是Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 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的無參/有參請求
/**
* @param url 接口地址
* @param headers 請求頭
* @Description get請求
*/
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;
}請求實列:在這里無參請求就不展示,可自行試驗
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);請求結(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請求(application/x-www-form-urlencoded)
/**
* @param url 接口地址
* @param list NameValuePair(簡單名稱值對節(jié)點類型)類似html中的input
* @param headers 請求頭(默認(rèn)Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
* @Description post請求
*/
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;
}請求實列:
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);請求結(jié)果:
用戶名
1234
application/x-www-form-urlencoded; charset=UTF-8
Post請求(application/json)
/**
* @param url 接口地址
* @param jsonString json字符串
* @param headers 請求頭(默認(rèn)Content-Type:application/json; charset=UTF-8)
* @Description post Json 請求
*/
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;
}請求實列:
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);請求結(jié)果:

Get請求url拼接
/**
* @param url 接口地址(無參數(shù)/有參)
* @param params 拼接參數(shù)集合
* @Description get請求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();
}
請求實列:
Map<String, String> params = new HashMap<>();
params.put("city", "重慶");
params.put("number", "手機(jī)號");
String appendUrl = getAppendUrl("https://TestGetSplice/index", params);
String appendUrl1 = getAppendUrl("https://TestGetSplice/index?a=33", params);
System.out.println(appendUrl);
System.out.println(appendUrl1);請求結(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平臺的每個實現(xiàn)上都可用。
import java.nio.charset.StandardCharsets; StandardCharsets.UTF_8
五、請求狀態(tài)常量
import org.apache.http.HttpStatus; // 200 HttpStatus.SC_OK
到此這篇關(guān)于java使用httpclient 發(fā)送請求的文章就介紹到這了,更多相關(guān)httpclient 發(fā)送請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于tomcat8 編寫字符編碼Filter過濾器無效問題的解決方法
下面小編就為大家分享一篇基于tomcat8 編寫字符編碼Filter過濾器無效問題的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
Java安全 ysoserial CommonsCollections2示例分析
這篇文章主要為大家介紹了Java安全 ysoserial CommonsCollections2示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
java 實現(xiàn)下壓棧的操作(能動態(tài)調(diào)整數(shù)組大小)
這篇文章主要介紹了java 實現(xiàn)下壓棧的操作(能動態(tài)調(diào)整數(shù)組大小),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
Retrofit+RxJava實現(xiàn)帶進(jìn)度下載文件
這篇文章主要為大家詳細(xì)介紹了Retrofit+RxJava實現(xiàn)帶進(jìn)度下載文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
Java使用分治算法實現(xiàn)排序數(shù)索引功能示例【二分搜索】
這篇文章主要介紹了Java使用分治算法實現(xiàn)排序數(shù)索引功能,結(jié)合具體實例形式分析了java分治算法進(jìn)行排序索引的相關(guān)操作技巧,需要的朋友可以參考下2017-09-09

