Java httpcomponents發(fā)送get post請(qǐng)求代碼實(shí)例
引入的包為:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.8</version> </dependency>
實(shí)現(xiàn)的工具類為:
import com.alibaba.fastjson.JSON;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpClientHelper {
private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
private HttpClientHelper() {
}
/**
* 發(fā)起POST請(qǐng)求
*
* @param url url
* @param paramMap 參數(shù)的Map格式
*/
public static void sendPost(String url, Map<String, String> paramMap) {
logger.info("開(kāi)始發(fā)起POST請(qǐng)求,請(qǐng)求地址為{},參數(shù)為{}", url, JSON.toJSON(paramMap));
CloseableHttpResponse response = null;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String encoding = "utf-8";
//創(chuàng)建post請(qǐng)求對(duì)象
HttpPost httpPost = new HttpPost(url);
//裝填請(qǐng)求參數(shù)
List<NameValuePair> list = new ArrayList<>();
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
//設(shè)置參數(shù)到請(qǐng)求對(duì)象中
httpPost.setEntity(new UrlEncodedFormEntity(list, encoding));
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
response = httpClient.execute(httpPost);
} catch (IOException e) {
logger.error("POST請(qǐng)求發(fā)出失敗,請(qǐng)求的地址為{},參數(shù)為{},錯(cuò)誤信息為{}", url, JSON.toJSON(paramMap), e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error("POST請(qǐng)求response關(guān)閉異常,錯(cuò)誤信息為{}", e.getMessage(), e);
}
}
}
/**
* 發(fā)起GET請(qǐng)求
*
* @param urlParam url請(qǐng)求,包含參數(shù)
*/
public static void sendGet(String urlParam) {
logger.info("開(kāi)始發(fā)起GET請(qǐng)求,請(qǐng)求地址為{}", urlParam);
HttpGet httpGet = new HttpGet(urlParam);
CloseableHttpResponse response = null;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
response = httpClient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
logger.error("GET請(qǐng)求發(fā)出成功,請(qǐng)求的地址為{},返回狀態(tài)為{}", urlParam, status);
} catch (IOException e) {
logger.error("GET請(qǐng)求發(fā)出失敗,請(qǐng)求的地址為{},錯(cuò)誤信息為{}", urlParam, e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error("GET請(qǐng)求response關(guān)閉異常,錯(cuò)誤信息為{}", e.getMessage(), e);
}
}
}
public static void main(String[] args) {
String url = "https://jiashubing.cn/tencenttest";
//需要傳入的參數(shù)
Map<String, String> map = new HashMap<>();
map.put("code", "js");
map.put("day", "0");
map.put("city", "北京");
map.put("dfc", "1");
map.put("charset", "utf-8");
sendPost(url, map);
String urlParam = "https://jiashubing.cn/talk/document?fileid=1234ji賈樹(shù)丙";
sendGet(urlParam);
}
}
如果POST請(qǐng)求想要發(fā)送Json 格式的數(shù)據(jù),只需要修改成這樣:
String json = JSON.toJSONString(paramMap);
StringEntity requestEntity = new StringEntity(json, "utf-8");
httpPost.setEntity(requestEntity);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java commons-httpclient如果實(shí)現(xiàn)get及post請(qǐng)求
- JAVA發(fā)送http get/post請(qǐng)求,調(diào)用http接口、方法詳解
- java模擬http的Get/Post請(qǐng)求,并設(shè)置ip與port代理的方法
- Java模擬HTTP Get Post請(qǐng)求實(shí)現(xiàn)論壇自動(dòng)回帖功能
- java發(fā)送http的get、post請(qǐng)求實(shí)現(xiàn)代碼
- java實(shí)現(xiàn)http的Post、Get、代理訪問(wèn)請(qǐng)求
- Java模擬HTTP Get Post請(qǐng)求 輕松實(shí)現(xiàn)校園BBS自動(dòng)回帖
- java使用httpclient模擬post請(qǐng)求和get請(qǐng)求示例
- Java 發(fā)送http請(qǐng)求(get、post)的示例
相關(guān)文章
springboot打成jar后獲取classpath下文件失敗的解決方案
這篇文章主要介紹了使用springboot打成jar后獲取classpath下文件失敗的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
idea報(bào)錯(cuò):java程序包c(diǎn)om.github.xiaoymin.knife4j.spring.annotations
這篇文章主要介紹了idea報(bào)錯(cuò):java程序包c(diǎn)om.github.xiaoymin.knife4j.spring.annotations不存在問(wèn)題解決,需要的朋友可以參考下2023-06-06
Java的作業(yè)調(diào)度類庫(kù)Quartz基本使用指南
這篇文章主要介紹了Java的作業(yè)調(diào)度類庫(kù)Quartz基本使用指南,Quartz能夠讓類按照指定的計(jì)劃順序執(zhí)行,需要的朋友可以參考下2016-03-03
springboot+springsecurity如何實(shí)現(xiàn)動(dòng)態(tài)url細(xì)粒度權(quán)限認(rèn)證
這篇文章主要介紹了springboot+springsecurity如何實(shí)現(xiàn)動(dòng)態(tài)url細(xì)粒度權(quán)限認(rèn)證的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Java數(shù)據(jù)結(jié)構(gòu)之鏈表詳解
本篇文章我們將講解一種新型的數(shù)據(jù)結(jié)構(gòu)—鏈表,鏈表是一種使用廣泛的通用數(shù)據(jù)結(jié)構(gòu),它可以用來(lái)作為實(shí)現(xiàn)棧,隊(duì)列等數(shù)據(jù)結(jié)構(gòu)的基礎(chǔ).文中有非常詳細(xì)的介紹,需要的朋友可以參考下2021-05-05
Spring基于注解管理bean實(shí)現(xiàn)方式講解
很多時(shí)候我們需要根據(jù)不同的條件在容器中加載不同的Bean,或者根據(jù)不同的條件來(lái)選擇是否在容器中加載某個(gè)Bean,這就是Bean的加載控制,一般我們可以通過(guò)編程式或注解式兩種不同的方式來(lái)完成Bean的管理2023-01-01

