zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    HDU 3549 基础网络流EK算法 Flow Problem
    HDU 1937 F
    HDU 1937 J
    HDU 1939 HE IS OFFSIDE
    HDU 3033 组合背包变形 I love sneakers!
    分组背包
    hdu1712 分组背包 ACboy needs your help
    hdu 1714 RedField
    HDU 1709 母函数天平问题 可出现减法的情况 The Balance
    HDU 1171 Big Event in HDU 母函数
  • 原文地址:https://www.cnblogs.com/carlo/p/10333283.html
Copyright © 2011-2022 走看看