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