http请求传参的几种类型

212 阅读3分钟

http请求传参的几种类型

首先看到postman的请求页面

image-20230507171211696.png

当我们不设置请求头时,使用 Params 传参时,参数是直接拼接在URL后面的,springboot中接收参数是这样的

    @PostMapping("/post/url")
    public String postUrl(String id, String name){
        log.info("id : {}, name:{}",id,name);
        return "success";
    }

当使用 Body 来传递参数时

image-20230507171518304.png

可以看到,有 以下几种传参方式,对应的是不同的 Content-Type

  • none:不设置,默认值
  • form-data:multipart/form-data
  • x-www-form-urlencoded:application/x-www-form-urlencoded
  • raw:application/json

form-data

通常用于表单提交,后台接口可以直接使用(String name)等接收单个参数,也可以使用 实体类来接收全部参数,注意这里的参数名或者实体类里的属性名称必须与传递的名称一致

    @PostMapping("/post/form")
    public String postForm(String id, String name, User user){
        log.info("id : {}, name:{}",id,name);
        return "success";
    }

x-www-form-urlencoded

参数被编码为名称/值对,接收参数的方式和 form-data 相同

application/json

最常用的传参方式,传递参数为json,后台必须使用 @RequestBody注解来接收参数。可以使用实体类或者 Map, 值得注意的是,@RequestBody注解在一个接口中只能有一个,多个不生效的

    @PostMapping("/post/json")
    public String postJson(@RequestBody User user){
        log.info("user : {}",user);
        return "success";
    }
    @PostMapping("/post/json")
    public String postJson(@RequestBody Map map){
        log.info("map : {}",map);
        return "success";
    }

RestTemplate构造请求

RestTemplate 是从 Spring3.0 开始支持的一个 http 请求工具,RestTemplate是Spring提供的用于访问Rest服务的客户端,它提供了很多可以方便访问远程http服务的方法,这些方法可以帮助开发人员减少编写客户端代码的工作量。

SpringFramework提供了一个RestTemplate模板工具类,对基于Http的客户端进行了封装,并且实现了对象与json的序列化和反序列化,非常方便

RestTemplate 是 Spring Resources 中一个访问第三方 RESTful API 接口的网络请求框架。 RestTemplate 的设计原则和其他 Spring Template (例如 JdbcTemplate、 JmsTemplate)类似,都 是为执行复杂任务提供了一个具有默认行为的简单方法。

RestTemplate 是用来消费 REST 服务的,所以 RestTemplate 的主要方法都与 REST 的 Http协议的一些方法紧密相连,例如 HEAD、 GET、 POST、 PUT、 DELETE 和 OPTIONS 等方法, 这些方法在 RestTemplate 类对应的方法为 headFor Headers()、 getForObject()、 postForObject()、 put()和 delete()等

  1. RestTemplate 默认是无法注入的,需要在配置类中直接new一个,或者自定义的各种参数,

       @Bean
       public RestTemplate restTemplate(){
          return new RestTemplate();
       }
    

    或者自定义他的各种参数

    @Configuration
    public class RestTemplateConfig {
     
        @Bean(name="httpClient")
        public CloseableHttpClient httpClient() {
            return HttpClientBuilder.create().build();
        }
     
        @Bean
        public RestTemplate restTemplate() {
            RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
            return restTemplate;
        }
     
        @Bean
        public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
            HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
            clientHttpRequestFactory.setHttpClient(httpClient());
            return clientHttpRequestFactory;
        }
     
        @Bean
        public TaskScheduler taskScheduler() {
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setThreadNamePrefix("poolScheduler");
            scheduler.setPoolSize(50);
            return scheduler;
        }
    }
    
  2. x-www-form-urlencoded 格式

    直接拼接在URL后面即可

  3. form-data 格式

     HttpHeaders headers = new HttpHeaders();
            HttpMethod method = HttpMethod.POST;
                // 设置以表单的方式提交
            headers.add("Content-Type",MediaType.MULTIPART_FORM_DATA_VALUE);
            headers.add("token","aaaaaa");
                //将请求头部和参数合成一个请求
            MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
            paramMap.add("status","aaa");
            paramMap.add("compere","aa");
            paramMap.add("meetingSummary",ccpcGroupZzsh.getMeetingSummary());
            paramMap.add("token",bhToken);
            HttpEntity< MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(paramMap, headers);
                //执行HTTP请求
            String url="http://"+host+"/test";
            ResponseEntity<String> response = restTemplate.exchange(url, method, requestEntity,String.class );
  4. json格式

      HttpHeaders headers = new HttpHeaders();
            HttpMethod method = HttpMethod.POST;
            // 设置以json的方式提交
            headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
            headers.add("token",loginUser.getBhToken());
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            //将请求头部和参数合成一个请求
            Map paramMap = new HashMap<>();
            paramMap.put("page",String.valueOf(pageParams.getCurrent()));
            paramMap.put("rows",String.valueOf(pageParams.getSize()));
            paramMap.put("userId",String.valueOf(memberId));
            JSONObject jsonObj = new JSONObject(paramMap);
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonObj.toString(), headers);
            //执行HTTP请求,将返回的结构使用ResultVO类格式化
            String url="http://"+host+"/test/json";
            String response = restTemplate.postForObject(url,  requestEntity,String.class );