Java httpcomponents發(fā)送get post請求代碼實例
引入的包為:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.8</version> </dependency>
實現(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請求
*
* @param url url
* @param paramMap 參數(shù)的Map格式
*/
public static void sendPost(String url, Map<String, String> paramMap) {
logger.info("開始發(fā)起POST請求,請求地址為{},參數(shù)為{}", url, JSON.toJSON(paramMap));
CloseableHttpResponse response = null;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String encoding = "utf-8";
//創(chuàng)建post請求對象
HttpPost httpPost = new HttpPost(url);
//裝填請求參數(shù)
List<NameValuePair> list = new ArrayList<>();
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
//設置參數(shù)到請求對象中
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請求發(fā)出失敗,請求的地址為{},參數(shù)為{},錯誤信息為{}", url, JSON.toJSON(paramMap), e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error("POST請求response關(guān)閉異常,錯誤信息為{}", e.getMessage(), e);
}
}
}
/**
* 發(fā)起GET請求
*
* @param urlParam url請求,包含參數(shù)
*/
public static void sendGet(String urlParam) {
logger.info("開始發(fā)起GET請求,請求地址為{}", 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請求發(fā)出成功,請求的地址為{},返回狀態(tài)為{}", urlParam, status);
} catch (IOException e) {
logger.error("GET請求發(fā)出失敗,請求的地址為{},錯誤信息為{}", urlParam, e.getMessage(), e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error("GET請求response關(guān)閉異常,錯誤信息為{}", 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賈樹丙";
sendGet(urlParam);
}
}
如果POST請求想要發(fā)送Json 格式的數(shù)據(jù),只需要修改成這樣:
String json = JSON.toJSONString(paramMap);
StringEntity requestEntity = new StringEntity(json, "utf-8");
httpPost.setEntity(requestEntity);
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Java commons-httpclient如果實現(xiàn)get及post請求
- JAVA發(fā)送http get/post請求,調(diào)用http接口、方法詳解
- java模擬http的Get/Post請求,并設置ip與port代理的方法
- Java模擬HTTP Get Post請求實現(xiàn)論壇自動回帖功能
- java發(fā)送http的get、post請求實現(xiàn)代碼
- java實現(xiàn)http的Post、Get、代理訪問請求
- Java模擬HTTP Get Post請求 輕松實現(xiàn)校園BBS自動回帖
- java使用httpclient模擬post請求和get請求示例
- Java 發(fā)送http請求(get、post)的示例
相關(guān)文章
使用Servlet Filter實現(xiàn)系統(tǒng)登錄權(quán)限
這篇文章主要為大家詳細介紹了使用Servlet Filter實現(xiàn)系統(tǒng)登錄權(quán)限,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-10-10
java使用JDBC動態(tài)創(chuàng)建數(shù)據(jù)表及SQL預處理的方法
這篇文章主要介紹了java使用JDBC動態(tài)創(chuàng)建數(shù)據(jù)表及SQL預處理的方法,涉及JDBC操作數(shù)據(jù)庫的連接、創(chuàng)建表、添加數(shù)據(jù)、查詢等相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2017-08-08
關(guān)于maven install報錯原因揭秘:parent.relativePath指向錯誤的本地POM文件
在使用Maven進行項目構(gòu)建時,如果遇到'parent.relativePath'指向錯誤的本地POM文件的問題,可能會導致構(gòu)建失敗,這通常是由于父項目POM文件的相對路徑設置錯誤、本地POM文件與父項目POM文件版本或內(nèi)容不一致所致,解決方法包括檢查并修正父項目POM文件中的相對路徑設置2024-09-09
淺析Spring Boot中的spring-boot-load模塊
spring-boot-loader模塊允許我們使用java -jar archive.jar運行包含嵌套依賴jar的jar或者war文件,它提供了三種類啟動器。下面通過本文給大家介紹spring-boot-load模塊的相關(guān)知識,感興趣的朋友一起看看吧2018-01-01
Java實現(xiàn)多叉樹和二叉樹之間的互轉(zhuǎn)
本文主要介紹了Java實現(xiàn)多叉樹和二叉樹之間的互轉(zhuǎn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05

