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

​ 这些就是区别 其他的都一样按照请求体一样处理。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐