zoukankan      html  css  js  c++  java
  • Java发送Http带HEADER参数

    直接上代码:

    说明: 如果返回状态码200表示调用成功; 其他情况都返回null表示失败;

      /**
         * post with  json  and  head params
         *
         * @param url
         * @param headsMap
         * @param json
         * @return {@code  not null(maybe ""),statusCode=200(success) } {@code  null (fail)}
         */
        public static String httpPostWithJsonAndHeader(String url, String json, Map<String, String> headsMap) {
            String result = "";
            log.info("本次请求地址:{} ", url);
            log.info("本次传递数据:{}", json);
    
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(json, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            //
            if (headsMap != null && !headsMap.isEmpty()) {
                headsMap.forEach((key, value) -> {
                    httpPost.addHeader(key, value);
                });
            }
            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse response = httpClient.execute(httpPost)) {
    
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    log.info("HTTP请求成功!");
    
                    // 从响应模型中获取响应实体
                    HttpEntity responseEntity = response.getEntity();
                    if (responseEntity != null) {
                        result = EntityUtils.toString(responseEntity);
                    }
    
                } else {
                    log.info("HTTP请求失败!");
                    return null;
                }
    
                log.info("返回结果:{}", result);
                return result;
            } catch (Exception e) {
                log.error("HTTP请求出现异常4:", e);
                return null;
            }
        }
  • 相关阅读:
    测试开发之利器论战
    测试开发的战略战术
    Python日志Logging
    Android自动测试中的monkey工具使用方法
    ADB命令讲解
    学习要深入
    测试开发发展感触
    Web Service测试工具小汇
    python接口测试浅谈
    手机上app测试总结(转)
  • 原文地址:https://www.cnblogs.com/coloz/p/13031148.html
Copyright © 2011-2022 走看看