Java使用HttpClient實現Post請求

來源:互聯網
上載者:User

標籤:tco   core   .so   配置   com   代碼   依賴包   ams   實現   

    基於項目需求,想要實現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;}// 構建唯一會話Idpublic 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包(具體參見:http://bbs.umeng.com/thread-12187-1-1.html),隨尋找了Hadoop叢集中相關Jar包路徑,發現httpclient的相關依賴包為4.2.5,因此將pom.xml設定檔也更新為該版本,程式則運行通過.

 

Java使用HttpClient實現Post請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.