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);
}