1 前言
url如下:
https://openapi-fxg.jinritemai.com/product/list?app_key=691484656896&method=product.list&access_token=f907b16f-20a-84bd-d816aa64d0a0¶m_json={"check_status":"3","page":"0","size":"10","status":"0"}×tamp=2021-02-23+11%3A09%3A42&v=2&sign=ece9996a0225d380b7b6809ea851ae87
GET請求,使用postman或者直接復制到瀏覽器,都可以獲得請求回復內容。
但是使用Java restTemplate會提示“param_json非json格式,請檢查!”,后網上查詢得知當參數遇到{}為占位符,然而使用map裝載所有參數,url拼接每個參數的占位符app_key={app_key}&... 依舊不可以。
最后采用param_json的參數用占位符傳入,其它直接拼接,請求返回正確的數據。
2 代碼
map.put("page", "0"); map.put("size", "10"); map.put("status", "0"); map.put("check_status", "3"); String paramJson = JSONObject.toJSONString(map); String accessToken = "f907a64d0a0"; String url = DOUDIAN_URL + "/product/list"; Date now = new Date(); String dateStr = DateUtils.format(now, DateUtils.DATE_TIME_PATTERN); String sign = fetchSign("product.list", paramJson, dateStr); String param = "?app_key=" + APP_KEY + "&method=" + "product.list" + "&access_token=" + accessToken + "¶m_json={param_json}×tamp=" + dateStr + "&v=2&sign=" + sign; Map<String, String> map2 = new HashMap<>(); map2.put("param_json", paramJson); System.out.println("url + param=" + url + param); String response = RequestUtils.getUrlWithParams(url + param, map2); JSONObject jsonObject = JSONObject.parseObject(response); if (jsonObject.getIntValue("err_no") == 0) { return jsonObject.getJSONObject("data"); } else { System.out.println("jsonObject=" + jsonObject.toJSONString()); } return null; } public static String fetchSign(String methodName, String paramJson, String timeStamp) { String requestStr = APP_SECRET + "app_key" + APP_KEY + "method" + methodName + "param_json" + paramJson + "timestamp" + timeStamp + "v2" + APP_SECRET; return stringToMD5(requestStr); } /** * 將param參數轉成MD5 * * @param plainText 請求參數 * @return String */ public static String stringToMD5(String plainText) { byte[] secretBytes = null; try { secretBytes = MessageDigest.getInstance("md5").digest( plainText.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("沒有這個md5算法!"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("沒有UTF-8編碼"); } StringBuilder md5code = new StringBuilder(new BigInteger(1, secretBytes).toString(16)); while (md5code.length() < 32) { md5code.insert(0, "0"); } return md5code.toString(); }
3 參考
[1] Java RestTemplate post請求傳遞參數遇到的坑
[2] restTemplate的GET請求 ,url中的參數使用占位符
[3] RestTemplate的異常:Not enough variables available to expand