RestTemplate 调用远程方法,服务端要求接受参数类型:application/x-www-form-urlencoded
程序员文章站
2024-03-20 21:49:16
...
RestTemplate 调用远程方法,服务端要求接受参数类型:application/x-www-form-urlencoded
解释:是一个表单请求
public APIResult postWithParamNoToken2(String url, JSONObject params) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
String appKey = params.getString("appKey");
String appSecret = params.getString("appSecret");
// 设置请求参数
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
postParameters.put("appKey", Collections.singletonList(appKey));
postParameters.put("appSecret", Collections.singletonList(appSecret));
HttpEntity<Object> req = new HttpEntity<>(postParameters, headers);
ResponseEntity<APIResult> response =
restTemplate.exchange(url, HttpMethod.POST, req, APIResult.class);
if (response.getStatusCodeValue() == 200) {
response.getBody();
return response.getBody();
} else {
APIResult apiResult = new APIResult();
apiResult.setOk(false);
apiResult.setErrorCode(500);
return apiResult;
}
}
注释:
1.请求头类型 application/x-www-form-urlencoded
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
2.请求参数类型:MultiValueMap
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
postParameters.put("appKey", Collections.singletonList(appKey));
postParameters.put("appSecret", Collections.singletonList(appSecret));
这些就是区别 其他的都一样按照请求体一样处理。
上一篇: MySql主从复制