• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

RestTemplate 防坑指南

武飞扬头像
shxex
帮助1

401 nobody

请求体编码需要要对应的消息体转换器

    private List<HttpMessageConverter<?>> getConverts() {
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        // String转换器
        StringHttpMessageConverter stringConvert = new StringHttpMessageConverter();
        List<MediaType> stringMediaTypes = new ArrayList<MediaType>() {{
            //添加响应数据格式,不匹配会报401
            add(MediaType.TEXT_PLAIN);
            add(MediaType.TEXT_HTML);
            add(MediaType.APPLICATION_JSON);
        }};
        stringConvert.setSupportedMediaTypes(stringMediaTypes);
        messageConverters.add(stringConvert);
        return messageConverters;
    }

表单请求

restTemplate 的表单请求必须使用MultiValueMap提交参数

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("key","value");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> param = new 		HttpEntity<>(map, headers);

JSON 请求

请求会把请求体转成 json格式,安装需要的json格式定义实体即可。

        //请求参数
        Map<String, Object> map = new HashMap<>();
        map.put("username", LOGIN_USER_NAME);
        map.put("password", LOGIN_PWD);
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //构造请求体
        HttpEntity<Map<String, Object>> param = new HttpEntity<>(map, headers);
        //构造回应体
        ParameterizedTypeReference<IotR<ObjectNode>> typeRef =
                new ParameterizedTypeReference<IotR<ObjectNode>>() {
                };
        IotR<ObjectNode> responseData = restTemplate.exchange(LOGIN_URL, HttpMethod.POST, param, typeRef).getBody();

url参数请求

参数需要在url中使用占位符,把参数封装在Map中传递给Map<String, ?> uriVariables 编码,不然会有奇怪的问题出现。

        //构造请求
        HashMap<String,Object> map = new HashMap<>();
        map.put("customName",customName);
        map.put("everyDay",everyDay);
        ParameterizedTypeReference<AirR<AirBatchData>> typeRef = new ParameterizedTypeReference<AirR<AirBatchData>>() {};
        String url = AIR_DATA_BATCH_URL
                  "?customName={customName}"
                  "&everyDay={everyDay}";
        ResponseEntity<AirR<AirBatchData>> forEntity = restTemplate.exchange(url, HttpMethod.GET, null, typeRef,map);

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbhjij
系列文章
更多 icon
同类精品
更多 icon
继续加载