RestTemplate 调用远程方法,服务端要求接受参数类型:application/x-www-form-urlencoded
RestTemplate 调用远程方法,服务端要求接受参数类型:application/x-www-form-urlencoded解释:是一个表单请求public APIResult postWithParamNoToken2(String url, JSONObject params) {HttpHeaders headers = new HttpHeaders();headers.setCon
·
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));
这些就是区别 其他的都一样按照请求体一样处理。
更多推荐
已为社区贡献2条内容
所有评论(0)