java RestTemplate post请求加json参数
public String geturl() throws Exception {
CommonResult commonResult = new CommonResult();
try {
RestTemplate restTemplate = new RestTemplate(generateHttpRequestFactory());
JSONObject json=new JSONObject();
json.put("username",username);
json.put("password",password);
Map<String, String > heads = new HashMap<>();
heads.put("Content-Type", "application/json;charset=UTF-8");
HttpResponse httpResponse = HttpRequest.post(url+"/login") // url
.headerMap(heads, false) // 请求头设置
.body(json.toJSONString()) // json参数
.timeout(5 * 60 * 1000) // 超时
.execute(); // 请求
System.out.println("获取返回服务器的状态码:----- " + httpResponse.getStatus() );
System.out.println("获取返回服务器的状态码:----- " + httpResponse );
Map<String, String> requestBody = new HashMap<>();
requestBody.put("username",username);
requestBody.put("password",password);
HttpHeaders requestHeaders = new HttpHeaders();
// 重点是配置请求头内容类型为:"application/json"
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, String>> r = new HttpEntity<>(requestBody, requestHeaders);
String data= restTemplate.postForObject(url+"/login", r, String.class);
System.out.println(data);