Java HttpClient4.5.2发送post请求示例

public static Map<String, Object> invokeCapp(String URL, Map paramMap) throws Exception {
    Map map = new HashMap();
    
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(2000) // 设置连接超时时间,单位毫秒
            .setConnectionRequestTimeout(1000)
            .setSocketTimeout(5000) // 请求获取数据的超时时间,单位毫秒
            .build();
    HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    };
    CloseableHttpClient client = HttpClients.custom()
            .setDefaultRequestConfig(requestConfig)
            .setRetryHandler(myRetryHandler)
            .build();
    
    try {
        JSONObject paramJson = new JSONObject(paramMap);
        StringEntity paramEntity = new StringEntity(paramJson.toString(), "UTF-8"); // 对参数进行编码
        paramEntity.setContentType("application/x-www-form-urlencoded; charset=utf-8");
//            paramEntity.setContentType("application/json; charset=utf-8");
        
        HttpPost httpPost = new HttpPost(URL);
        httpPost.setEntity(paramEntity);
        httpPost.setConfig(requestConfig);
        
        CloseableHttpResponse response = client.execute(httpPost);
        
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String responseStr = EntityUtils.toString(entity, "UTF-8");
            logger.info("RequestUtils - responseStr <== " + responseStr);
            if (StringHelper.isEmpty(responseStr)) {
                responseStr = "{}";
            }
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("RequestUtils - statusCode <== " + statusCode);
            if (HttpServletResponse.SC_OK == statusCode) {
                JSONObject dataJson = (JSONObject) JSONObject.parse(responseStr);
                map = new HashMap(dataJson);
            } else {
                logger.info("RequestUtils - invokeCapp <== " + responseStr);
                return map;
            }
        }
        response.close();
    } finally {
        client.close();
    }

    return map;
}

 

posted @ 2019-01-29 11:31  carlo-z  阅读(5162)  评论(0编辑  收藏  举报