1、httpClient文章来源:https://www.toymoban.com/news/detail-535667.html
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可以这样添加文章来源地址https://www.toymoban.com/news/detail-535667.html
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> request = new HttpEntity<>(body, headers);
// 使用RestTemplate请求
RestTemplate restTemplateHttps = new RestTemplate();
ResponseEntity<JSONObject> responseBody = restTemplateHttps.postForEntity(url, request, JSONObject.class);
JSONObject httpBody = responseBody.getBody();
System.out.println("接口返回参数:" + httpBody);
}
到了这里,关于restTemplate添加header的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!