【前言】
今天在调用快递接口的时候,值总是返回400,一直在想为什么返回400,后来找到官方,官方是这么说的。意思是请求头的格式的问题,但是我的请求头就是这个啊,那么为什么呢?
【解决思路】
// 设置请求头
HttpHeaders headers = new HttpHeaders();
// MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded");
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
我的请求头就是
public static final MediaType APPLICATION_FORM_URLENCODED = new MediaType("application", "x-www-form-urlencoded");
但是还是一直返回400,查了很多资料直到看到了下面的内容。
才明白,我之前用的是JSON的形式提交的。那么我们换成表单的形式提交即可。下面是完整的代码,代码中也有写怎么将表单提交改成JSON提交的形式。
Map<String, String> params = new HashMap<String, String>();
params.put("com", "yuantong");
params.put("phone","13868688888");
params.put("from","广东省深圳市南山区");
params.put("to","北京市朝阳区");
params.put("resultv2","1");
params.put("show","0");
params.put("order","desc");
//secret_code,接口编号
params.put("num", "YT5264672303655");
String string = JSONObject.toJSONString(params);
String sign = SignUtils.querySign(string, "dvOxcmsb7709", "0D4ED150318D0E634C8F14AE99D0AB3A");
String url="https://poll.kuaidi100.com/poll/query.do";
// 设置请求头
HttpHeaders headers = new HttpHeaders();
// MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded");
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
RestTemplate restTemplate=new RestTemplate();
// Map<String, String> jsonOb = new HashMap<String, String>();
// JSONObject jsonOb = new JSONObject();
// jsonOb.put("customer","0D4ED150318D0E634C8F14AE99D0AB3A");
// jsonOb.put("sign",sign);
// jsonOb.put("param",JSONObject.toJSONString(params));
MultiValueMap<String,String> jsonOb = new LinkedMultiValueMap<String,String>();
jsonOb.add("customer","0D4ED150318D0E634C8F14AE99D0AB3A");
jsonOb.add("sign",sign);
jsonOb.add("param",JSONObject.toJSONString(params));
// HttpEntity<String> httpEntity = new HttpEntity<String>(jsonOb, headers);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(jsonOb, headers);
//获取返回数据
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
// String body = restTemplate.postForObject(url, httpEntity, String.class);
// String post = post(jsonOb);
System.out.println(response);