java使用httpclient 發(fā)送請(qǐng)求的示例
HttpClient 是Apache Jakarta Common 下的子項(xiàng)目,可以用來(lái)提供高效的、最新的、功能豐富的支持 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的無(wú)參/有參請(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í)列:在這里無(wú)參請(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": "中國(guó)",
"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 接口地址(無(wú)參數(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通過(guò)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通過(guò)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)文章
idea 打包的jar運(yùn)行報(bào) "XXX中沒有主清單屬性"
這篇文章主要介紹了idea 打包的jar運(yùn)行報(bào) "XXX中沒有主清單屬性",文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03基于tomcat8 編寫字符編碼Filter過(guò)濾器無(wú)效問(wèn)題的解決方法
下面小編就為大家分享一篇基于tomcat8 編寫字符編碼Filter過(guò)濾器無(wú)效問(wèn)題的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01Java安全 ysoserial CommonsCollections2示例分析
這篇文章主要為大家介紹了Java安全 ysoserial CommonsCollections2示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11java 實(shí)現(xiàn)下壓棧的操作(能動(dòng)態(tài)調(diào)整數(shù)組大小)
這篇文章主要介紹了java 實(shí)現(xiàn)下壓棧的操作(能動(dòng)態(tài)調(diào)整數(shù)組大小),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02Retrofit+RxJava實(shí)現(xiàn)帶進(jìn)度下載文件
這篇文章主要為大家詳細(xì)介紹了Retrofit+RxJava實(shí)現(xiàn)帶進(jìn)度下載文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05Springboot框架實(shí)現(xiàn)自動(dòng)裝配詳解
在使用springboot時(shí),很多配置我們都沒有做,都是springboot在幫我們完成,這很大一部分歸功于springboot自動(dòng)裝配。本文將詳細(xì)為大家講解SpringBoot的自動(dòng)裝配原理,需要的可以參考一下2022-08-08Java使用分治算法實(shí)現(xiàn)排序數(shù)索引功能示例【二分搜索】
這篇文章主要介紹了Java使用分治算法實(shí)現(xiàn)排序數(shù)索引功能,結(jié)合具體實(shí)例形式分析了java分治算法進(jìn)行排序索引的相關(guān)操作技巧,需要的朋友可以參考下2017-09-09