RestTemplate 调用远程方法,服务端要求接受参数类型:application/x-www-form-urlencoded

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值