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;
            }
        }
  • 相关阅读:
    springboot启动后执行某些动作
    Virtualbox的nat网络
    xshell6
    day01 K8S
    Nginx的日志文件切割
    virtualbox磁盘空间大小调整
    装修柜子木台面
    mybatis 批量in 多个字段写法
    jenkins shell常用配置
    activiti工作流引擎数据库表结构
  • 原文地址:https://www.cnblogs.com/coloz/p/13031148.html
Copyright © 2011-2022 走看看