Java代碼發(fā)送post請求實現(xiàn)方式
更新時間:2026年05月09日 10:03:04 作者:胡大可呀
本文介紹了使用Java發(fā)送POST請求的方法,包括引用工具類、設(shè)置訪問地址、請求頭和json請求體,最后使用工具類發(fā)送請求并返回結(jié)果
使用Java代碼訪問對應(yīng)連接,并發(fā)送json格式數(shù)據(jù),post請求。
1、首先引用工具類HttpClientUtil
/*
* 利用HttpClient進(jìn)行post請求的工具類
*/
public class HttpClientUtil {
public String doPost(String url, Map<String, String> headerMap, String jsonText, String charset) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
InputStream in = null;
try {
httpClient = SSLClientFactory.createSSLClientDefault();
httpPost = new HttpPost(url);
// 設(shè)置參數(shù)
Iterator<Entry<String, String>> iterator = headerMap.entrySet().iterator();
Entry<String, String> elem = null;
while (iterator.hasNext()) {
elem = iterator.next();
httpPost.addHeader(elem.getKey(), elem.getValue());
}
if (StringUtils.isNotBlank(jsonText)) {
byte[] bytes = jsonText.getBytes(HTTP.UTF_8);
ByteArrayEntity se = new ByteArrayEntity(bytes);
httpPost.setEntity(se);
}
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
in=resEntity.getContent();
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
}
finally
{
if (in != null){
try
{
in.close ();
}
catch (IOException e)
{
e.printStackTrace ();
}
}
}
return result;
}
}2、獲取 訪問地址、請求頭、json格式的請求體
//獲取接口地址
String url="http://external.rmcp-zsh.bosafe.com/api/v1/ztexternal/user/change";
//獲取請求頭
Map<String, String> headerMap = new HashMap<String, String>();
headerMap.put("appId", appId);
headerMap.put("randomNumber",s);
headerMap.put("timestamp", strTime);
headerMap.put("signature", w );
headerMap.put("Content-Type", "application/json");
//獲取請求體
JSONObject obj = new JSONObject();
obj.put("appId", appId);
//將待同步對象集合轉(zhuǎn)換為json數(shù)據(jù)
JSONArray userList = JSONUtil.parseArray(split);
//設(shè)置請求體參數(shù)
obj.put("userList",userList);3、利用工具類HttpClientUtil 訪問 并返回結(jié)果
HttpClientUtil httpClientUtil = new HttpClientUtil();
//發(fā)送post請求
String results = httpClientUtil.doPost(url, headerMap, obj.toJSONString(), Constants.UTF8);
//返回結(jié)果
JSONObject resultJson = JSONObject.parseObject(results);
String status =resultJson.getString("status");總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Java中使用externds關(guān)鍵字繼承類的用法
子類使用extends繼承父類是Java面向?qū)ο缶幊讨械幕A(chǔ)知識,這里我們就來詳解Java中使用externds關(guān)鍵字繼承類的用法,需要的朋友可以參考下2016-07-07
解決@ResponseBody作用在返回類型為String的方法時的坑
這篇文章主要介紹了解決@ResponseBody作用在返回類型為String的方法時的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
SpringBoot應(yīng)用自定義logback日志詳解
默認(rèn)情況下,SpringBoot內(nèi)部使用logback作為系統(tǒng)日志實現(xiàn)的框架,將日志輸出到控制臺,不會寫到日志文件。本篇文章主要講解下如何自定義logabck.xml以及對logback文件中配置做一個詳解,需要的可以參考一下2022-10-10
Spring之底層架構(gòu)核心概念Environment及用法詳解
這篇文章主要介紹了Spring之底層架構(gòu)核心概念-Environment,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12

