Java使用HttpClient實(shí)現(xiàn)Post請(qǐng)求實(shí)例
基于項(xiàng)目需求,想要實(shí)現(xiàn)Post消息推送,故采用HttpClient組件進(jìn)行實(shí)現(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è)置超時(shí)時(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)建消息實(shí)體 StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); // 發(fā)送Json格式的數(shù)據(jù)請(qǐng)求 entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = httpClient.execute(post); // 檢驗(yàn)返回碼 int statusCode = response.getStatusLine().getStatusCode(); if(statusCode != HttpStatus.SC_OK){ LogUtil.info("請(qǐng)求出錯(cuò): "+statusCode); isSuccess = false; }else{ int retCode = 0; String sessendId = ""; // 返回碼中包含retCode及會(huì)話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)建唯一會(huì)話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集群進(jìn)行發(fā)送POST請(qǐng)求時(shí),遇到"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集群運(yùn)行程序時(shí),首先會(huì)加載自己相關(guān)目錄下的jar包,在自己目錄下如果未找到,才會(huì)加載程序運(yùn)行時(shí)指定的jar包,隨查找了Hadoop集群中相關(guān)Jar包路徑,發(fā)現(xiàn)httpclient的相關(guān)依賴包為4.2.5,因此將pom.xml配置文件也更新為該版本,程序則運(yùn)行通過.
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java使用httpclient 發(fā)送請(qǐng)求的示例
- java?11新特性HttpClient主要組件及發(fā)送請(qǐng)求示例詳解
- Java通過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通過HttpClient發(fā)送HTTP請(qǐng)求的方法示例
- java實(shí)現(xiàn)HttpClient異步請(qǐng)求資源的方法
- Java高并發(fā)場(chǎng)景下的 HttpClient請(qǐng)求優(yōu)化實(shí)現(xiàn)
相關(guān)文章
Spring中的事務(wù)管理及實(shí)現(xiàn)方式解析
這篇文章主要介紹了Spring中的事務(wù)管理及實(shí)現(xiàn)方式解析,Spring事務(wù)管理基于底層數(shù)據(jù)庫本身的事務(wù)處理機(jī)制,數(shù)據(jù)庫事務(wù)的基礎(chǔ),是掌握Spring事務(wù)管理的基礎(chǔ),這篇總結(jié)下Spring事務(wù),需要的朋友可以參考下2024-01-01Java 高并發(fā)七:并發(fā)設(shè)計(jì)模型詳解
本文主要介紹Java高并發(fā) 并發(fā)設(shè)計(jì)模型的知識(shí),這里主要講解 1. 什么是設(shè)計(jì)模式 2. 單例模式 3. 不變模式 4. Future模式 5. 生產(chǎn)者消費(fèi)者,有需要的小伙伴可以參考下2016-09-09解析ConcurrentHashMap:成員屬性、內(nèi)部類、構(gòu)造方法
ConcurrentHashMap是由Segment數(shù)組結(jié)構(gòu)和HashEntry數(shù)組結(jié)構(gòu)組成。Segment的結(jié)構(gòu)和HashMap類似,是一種數(shù)組和鏈表結(jié)構(gòu),今天給大家普及java面試常見問題---ConcurrentHashMap知識(shí),一起看看吧2021-06-06