java接受http請求接口帶參

下面以http post的方式舉例,我還寫了一個小demo提供大家參考,裏面有http get的方式。還有就是需要兩個jar包httpclient-4.3.jar,httpcore-4.3.jar一定要注意版本。

 /**
      * http post調用接口
      * @param url 請求地址  headerMap 請求頭 paramMap請求參數
      * @return
      * @throws Exception
      */
public static String httpPost(String url, Map<String, String> headerMap, Map<String, String> paramMap) throws Exception {
    String result = null;
    CloseableHttpResponse response = null;
    ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            long keepAlive = super.getKeepAliveDuration(response, context);
            if (keepAlive == -1) {
                // Keep connections alive 60 seconds if a keep-alive value
                // has not be explicitly set by the server
                keepAlive = 1000L * 60;
            }
            return keepAlive;
        }
    };
    
    CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(keepAliveStrategy).build();
    HttpPost httpPost = new HttpPost(url);
    try {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).setConnectionRequestTimeout(20000).build();
        httpPost.setConfig(requestConfig);
        // 設置HTTP頭
        if(headerMap != null && headerMap.size() > 0) {
            for(String key : headerMap.keySet()) {
                httpPost.addHeader(key, headerMap.get(key));
            }
        }
        if(paramMap != null && paramMap.size() > 0) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for(String key : paramMap.keySet()) {
                params.add(new BasicNameValuePair(key, paramMap.get(key)));
            }
            // 設置參數
            if (params != null && params.size() > 0) {
                // 將請求參數進行UTF-8編碼,以便傳輸中文
                httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            }
        }
        response = httpClient.execute(httpPost, new BasicHttpContext());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consumeQuietly(entity);
        } else {
            log.error("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
        }
    } catch (IOException e) {
        log.error("request url=" + url + ", exception, msg=" + e.getMessage(), e);
    } finally {
        httpPost.releaseConnection();
        try {
            httpClient.close();
        } catch (IOException e) {
            //log.error(e.getMessage(), e);
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
    return result;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章