httpclient工具类

 private void pushErrorData(List<ProductSyncLog> productSyncLogs) throws JsonProcessingException {
        if (CollectionUtil.isEmpty(productSyncLogs)){
            logger.info("没有数据要跟新");
            return;
        }
        List<String>  data = productSyncLogs.stream().map(ProductSyncLog::getErrorData).collect(Collectors.toList());
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        List<OutPutResult> outPutResults = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(data)){
            for (String s : data) {
                List<OutPutResult> outPutResults1 = JSONObject.parseArray(s, OutPutResult.class);
                if (CollectionUtil.isNotEmpty(outPutResults1)){
                    outPutResults.addAll(outPutResults1);
                }
            }
        }

        String interfaceUrl = "/datacenter/sku/synError";
        String completeUrl = url + interfaceUrl;
        HttpPost httpPost = new HttpPost(completeUrl);

        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(outPutResults);
        StringEntity entity = new StringEntity(s, "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            logger.info("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                logger.info("响应内容长度为:" + responseEntity.getContentLength());
                logger.info("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            logger.info(e.toString());
        } catch (ParseException e) {
            logger.info(e.toString());
        } catch (IOException e) {
            logger.info(e.toString());
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
上一篇:C#5.0异步编程 HttpClient IP代理验证原码


下一篇:Go - httpclient 常用操作