• 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;
            }
        }
  • 相关阅读:
    设计模式-享元模式
    设计模式-外观模式
    设计模式-桥接模式
    设计模式-适配器模式
    设计模式-代理模式
    java设计模式中用到的UML图
    VS code 初次安装配置
    CMD部分操作、BAT、以及VS SQL部分快捷键
    网络部分
    CMD 中certutil 操作命令
  • 原文地址:https://www.cnblogs.com/coloz/p/13031148.html
Copyright © 2020-2023  润新知