Java使用HttpClient實現Post請求實例。本站提示廣大學習愛好者:(Java使用HttpClient實現Post請求實例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java使用HttpClient實現Post請求實例正文
基於項目需求,想要實現Post消息推送,故采用HttpClient組件進行實現,相關代碼如下(注:程序采用的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(); // 設置超時時間 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000); post = new HttpPost(url); // 構造消息頭 post.setHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Connection", "Close"); String sessionId = getSessionId(); post.setHeader("SessionId", sessionId); post.setHeader("appid", appid); // 構建消息實體 StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); // 發送Json格式的數據請求 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; } // 構建唯一會話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集群進行發送POST請求時,遇到"java.lang.NoSuchFieldError: INSTANCE"的問題,此類問題一般是"jar包沖突"的問題所致,但奇怪的是本地的pom.xml設置的依賴包中有該字段,相關的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>
隨後在網上查找了一翻,找到問題的緣由,原因在於Hadoop集群運行程序時,首先會加載自己相關目錄下的jar包,在自己目錄下如果未找到,才會加載程序運行時指定的jar包,隨查找了Hadoop集群中相關Jar包路徑,發現httpclient的相關依賴包為4.2.5,因此將pom.xml配置文件也更新為該版本,程序則運行通過.
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。