java分别发送post请求application/x-www-form-urlencoded和application/json类型数据

有时候我们在postman上调用接口它可以正常返回结果,但是自己写后端代码时报400错误时,这可能就是对请求头的Content-Type没有设置的结果。

post提交数据有多种方式,而application/x-www-form-urlencoded和application/json都是比较常见的方式。

x-www-form-urlencoded是表单提交的一种,表单提交还包括multipart/form-data。以 application/x-www-form-urlencoded 方式提交数据,会将表单内的数据转换为键值对。以multipart/form-data方式提交数据,是使用包含文件上传控件的表单。

application/json类型的post提交

        String url="https://localhost:8080/poll/query.do";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate=new RestTemplate();

        JSONObject forms = new JSONObject();

        forms.put("customer", "123");
        forms.put("sign", "123");

        HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(forms), headers);

        //获取返回数据
        String body = restTemplate.postForObject(url, httpEntity, String.class);

x-www-form-urlencoded类型的post提交

        String url="https://localhost:8080/poll/query.do";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        RestTemplate restTemplate=new RestTemplate();

        MultiValueMap<String, String> forms= new LinkedMultiValueMap<String, String>();

        forms.put("customer", Collections.singletonList("123"));
        forms.put("sign", Collections.singletonList("123"));

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(forms, headers);

        //获取返回数据
        String body = restTemplate.postForObject(url, httpEntity, String.class);

猜你喜欢

转载自blog.csdn.net/liangjiabao5555/article/details/114411209