资讯详情

restTemplate添加header

1、httpClient

public static void main(String[] args) throws Exception { 
                 HashMap<String, String> hashMap = new HashMap<>();         hashMap.put("key", "value");         String body = JSONObject.toJSONString(hashMap);         post(body);     }      /** * 发送 post请求 */     public static void post(String body) throws Exception { 
                 // 获得Http客户端         CloseableHttpClient httpclient = HttpClientBuilder.create().build();          // 创建httpPost         HttpPost httppost = new HttpPost("替换连接地址");         //设置参数体         httppost.setHeader("Content-Type", "application/json;charset=UTF-8");          ///装填参数         StringEntity s = new StringEntity(body, "utf-8");          ///设置参数到请求对象         httppost.setEntity(s);

        CloseableHttpResponse response = httpclient.execute(httppost);
        try { 
       

            HttpEntity entity = response.getEntity();
            if (entity != null) { 
       
                System.out.println("--------------------------------------");
                System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                System.out.println("--------------------------------------");
            }
        } finally { 
       
            response.close();
        }
        try { 
       
            httpclient.close();
        } catch (IOException e) { 
       
            e.printStackTrace();
        }
    }

2、restTemplate header可以这样添加

public static void main(String[] args) throws Exception { 
       

        String url = "替换连接地址";

        // 请求体
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key", "value");
        String body = JSONObject.toJSONString(hashMap);

        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json;charset=UTF-8");
     
        // 请求
        HttpEntity<String> requst = new HttpEntity<>(body, headers);

        // 使用RestTemplate请求
        RestTemplate restTemplateHttps = new RestTemplate();
        ResponseEntity<JSONObject> responseBody = restTemplateHttps.postForEntity(url, requst, JSONObject.class);

        JSONObject httpBody = responseBody.getBody();
        System.out.println("接口返回参数:" + httpBody);
    }

标签: header11连接器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台