• resttemplate使用post 方式 同时提交formData 和body 数据


    网上很多方式使用resttemplate提交的时候 在构造HttpEntity对象时 ,要么使用如下方法

    1 String jsonData = JSON.toJSONString(vo);
    2         HttpHeaders headers = new HttpHeaders();
    3         headers.setContentType(MediaType.APPLICATION_JSON);
    4         HttpEntity<String> request = new HttpEntity<>(jsonData, headers);
    ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);

    此方法  json 出现在body 体里面

    还有一种方法  提交formdata的方式,构造一个map  如下:

            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("method", UPLOAD_METHOD);
            map.add("timestamp", timestamp + "");
            map.add("sign", SIGN);
            map.add("companyNo", companyNo);
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<String> request = new HttpEntity<>(map , headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);

    其实 post  提交分三种东东在里面 

    header 

    query  

    body

    而springboot 中 fromdata 是可以作为query 部分来提交的(其他框架不确定)

    如下

            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("method", UPLOAD_METHOD);
            map.add("timestamp", timestamp + "");
            map.add("sign", SIGN);
            map.add("companyNo", companyNo);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<>(jsonData, headers);
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiURL).queryParams(map);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(builder.toUriString(), request, JSONObject.class);

    使用UriComponentsBuilder  将map构造在url里面

  • 相关阅读:
    30个在线学习设计与开发的站点
    马云:你的一生到底该往哪个方向走?
    那些争议最大的编程观点
    Python 标识符
    Python 环境搭建
    Python 简介
    PyCharm 使用技巧
    Shell脚本———— /dev/null 2>&1详解
    linux 创建连接命令 ln -s 软链接
    scp命令详解
  • 原文地址:https://www.cnblogs.com/niceletter/p/11822390.html
Copyright © 2020-2023  润新知