1. 程式人生 > >HttpClient傳送put與post請求程式碼例項與解析

HttpClient傳送put與post請求程式碼例項與解析

    /**
     * 例項化HttpClient
     * maxTotal  最大連線數
     * maxPerRoute  最大併發量
     * socketTimeout  從伺服器讀取資料超時時間
     * connectTimeout  和伺服器建立連線超時時間
     * connectionRequestTimeout  從連線池獲取連線的超時時間
     * @return
     */
    public static HttpClient createHttpClient(int maxTotal, int maxPerRoute, int socketTimeout, int connectTimeout,
                    int connectionRequestTimeout) {
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                        .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //設定整個連線池最大連線數 根據自己的場景決定
        cm.setMaxTotal(maxTotal);
        //這個是控制併發量的
        cm.setDefaultMaxPerRoute(maxPerRoute);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm)
                        .setDefaultRequestConfig(defaultRequestConfig).build();
        return httpClient;

    }

這裡的引數根據自己的實際情況來設定,這種呼叫一般都是外部呼叫,考慮到雙方協調性問題最好併發量不要設定特別大,呼叫不要特別頻繁,最好每天控制呼叫數量。

    public static String sendPostForCaice(HttpClient httpClient, String url, Map<String, String> params, Charset encoding) {
        String resp = "";
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8"); 
        if (params != null && params.size() > 0) {
            StringEntity se = new StringEntity(JsonUtil.toJson(params), encoding);
            httpPost.setEntity(se);
        }
        CloseableHttpResponse response = null;
        try {
            response = (CloseableHttpResponse) httpClient.execute(httpPost);
            if(response!=null && 200 == response.getStatusLine().getStatusCode()){
            resp = EntityUtils.toString(response.getEntity(), encoding);
        }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return resp;
    }

該方法用於傳送post請求,JsonUtil.toJson(params)作用是把map轉換為json型別的String字串,最後傳送請求,得到返回結果

httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8"); 這個頭部資訊是根據雙方約定來設定。

    public static String sendPut(HttpClient httpClient, String url,String authorization,Map<String, String> params,Charset encoding){
    HttpPut httpPut = new HttpPut(url);
    //header存放 LPCC_TOKEN 
        httpPut.addHeader(Const.AUTHORIZATION,"jwt "+authorization);
        httpPut.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8"); 
        if (params != null && params.size() > 0) {
            StringEntity se = new StringEntity(JsonUtil.toJson(params), encoding);
            httpPut.setEntity(se);
        }
        HttpResponse httpResponse = null;
        String res =  null;
        try {
        httpResponse = httpClient.execute(httpPut);
        if(httpResponse!=null && 200 == httpResponse.getStatusLine().getStatusCode()){
    res =  EntityUtils.toString(httpResponse.getEntity(), encoding);
        }
} catch (ClientProtocolException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return res;
    }

該方法是傳送put請求,程式碼基本和post請求沒什麼區別。

這裡再說一下如果要傳送get請求,基本程式碼也是這樣,只是get請求不需要設定請求引數的StringEntity,引數都追加到url後面。