• 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;
    }
  • 相关阅读:
    UVA Live Achrive 4327 Parade (单调队列,dp)
    从磁盘读取一个文件到内存中,再打印到控制台
    二分查找法
    日期:Date
    线程与进程
    泛型基本知识
    泛型
    Map集合的遍历方式:
    Arrays
    Set接口
  • 原文地址:https://www.cnblogs.com/carlo/p/10333283.html
Copyright © 2020-2023  润新知