Java使用HttpClient實現(xiàn)Post請求實例
基于項目需求,想要實現(xiàn)Post消息推送,故采用HttpClient組件進行實現(xiàn),相關(guān)代碼如下(注:程序采用的httpclient和httpcore依賴包的版本為4.2.5):
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import java.util.UUID;
import net.sf.json.JSONObject;
import java.nio.charset.Charset;
public static boolean httpPostWithJson(JSONObject jsonObj,String url,String appId){
boolean isSuccess = false;
HttpPost post = null;
try {
HttpClient httpClient = new DefaultHttpClient();
// 設(shè)置超時時間
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
post = new HttpPost(url);
// 構(gòu)造消息頭
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Close");
String sessionId = getSessionId();
post.setHeader("SessionId", sessionId);
post.setHeader("appid", appid);
// 構(gòu)建消息實體
StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 發(fā)送Json格式的數(shù)據(jù)請求
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
// 檢驗返回碼
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
LogUtil.info("請求出錯: "+statusCode);
isSuccess = false;
}else{
int retCode = 0;
String sessendId = "";
// 返回碼中包含retCode及會話Id
for(Header header : response.getAllHeaders()){
if(header.getName().equals("retcode")){
retCode = Integer.parseInt(header.getValue());
}
if(header.getName().equals("SessionId")){
sessendId = header.getValue();
}
}
if(ErrorCodeHelper.IAS_SUCCESS != retCode ){
// 日志打印
LogUtil.info("error return code, sessionId: "sessendId"\t"+"retCode: "+retCode);
isSuccess = false;
}else{
isSuccess = true;
}
}
} catch (Exception e) {
e.printStackTrace();
isSuccess = false;
}finally{
if(post != null){
try {
post.releaseConnection();
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return isSuccess;
}
// 構(gòu)建唯一會話Id
public static String getSessionId(){
UUID uuid = UUID.randomUUID();
String str = uuid.toString();
return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
}
Ps: 在使用Hadoop集群進行發(fā)送POST請求時,遇到"java.lang.NoSuchFieldError: INSTANCE"的問題,此類問題一般是"jar包沖突"的問題所致,但奇怪的是本地的pom.xml設(shè)置的依賴包中有該字段,相關(guān)的httpclient依賴包如下:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.1</version> </dependency>
隨后在網(wǎng)上查找了一翻,找到問題的緣由,原因在于Hadoop集群運行程序時,首先會加載自己相關(guān)目錄下的jar包,在自己目錄下如果未找到,才會加載程序運行時指定的jar包,隨查找了Hadoop集群中相關(guān)Jar包路徑,發(fā)現(xiàn)httpclient的相關(guān)依賴包為4.2.5,因此將pom.xml配置文件也更新為該版本,程序則運行通過.
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解SpringBoot Mybatis如何對接多數(shù)據(jù)源
這篇文章主要為大家介紹了SpringBoot Mybatis如何對接多數(shù)據(jù)源實現(xiàn)方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
解決SpringBoot的@DeleteMapping注解的方法不被調(diào)用問題
這篇文章主要介紹了解決SpringBoot的@DeleteMapping注解的方法不被調(diào)用問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
淺談Java內(nèi)存區(qū)域與對象創(chuàng)建過程
下面小編就為大家?guī)硪黄獪\談Java內(nèi)存區(qū)域與對象創(chuàng)建過程。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
Java BigDecimal解決double精度丟失的問題
我們在日常開發(fā)中, 有很多時候會遇到小數(shù)(double類型)精確計算,本文主要介紹了Java BigDecimal解決double精度丟失的問題,具有一定的參考價值,感興趣的可以了解一下2023-11-11
JetBrains?發(fā)布下一代?IDE無比輕量幾秒就能啟動干活
雖然?JetBrains?公司說?Fleet?的定位和目標并不是代替其他?IDE,但個人覺得,?如果?Fleet?火起來了,其他?IDE?就會黯然失色,特別是多語言開發(fā)者,誰愿意裝多個?IDE?呢?到時候,可能?JetBrains?以后的所有?IDE?要一統(tǒng)江湖了2021-12-12
淺析java中 Spring MVC 攔截器作用及其實現(xiàn)
本篇文章主要介紹了java中SpringMVC 攔截器的使用及其實例,需要的朋友可以參考2017-04-04

