restTemplate添加header

时间:2025-03-20 07:32:23
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(); } }