有时候我们在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);
本文详细介绍了HTTP请求中Content-Type的两种常见类型:application/json和application/x-www-form-urlencoded。分别展示了如何在Java中使用RestTemplate进行这两种类型的POST请求,并指出未正确设置Content-Type可能导致的400错误。通过实例代码,解释了不同Content-Type在数据提交方式上的差异,对于理解HTTP请求和后端接口调用具有指导意义。
3286

被折叠的 条评论
为什么被折叠?



