【前言】
今天在呼叫快遞介面的時候,值總是回傳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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/265969.html
標籤:其他
