问题代码
@Slf4j
public class TestWechat {
public <T extends WxBaseReq, K extends WxBaseResp> K sendV3(T t, String method, Class<K> kClass) {
K k = null;
String body = JSON.toJSONString(t);
String apiUrl = "";//请求API
log.info("wechat http v3 requestUrl :{} ,body:{}", apiUrl, body);
ResponseEntity<K> responseEntity = null;
Long startTime = System.currentTimeMillis();
try {
// 有问题的地方
HttpEntity<T> entity = new HttpEntity<>(t, getHttpHeader("POST", apiUrl, body));
responseEntity = new RestTemplate().postForEntity(apiUrl, entity, kClass);
log.info("wechat http v3 response:{}", responseEntity);
if (responseEntity != null) {
k = responseEntity.getBody();
}
} catch (HttpClientErrorException e) {
log.info("wechat http v3 HttpClientErrorException:{}", e.getResponseBodyAsString());
throw e;
}
return k;
}
private HttpHeaders getHttpHeader(String method, String apiUrl, String body) {
//设置签名的请求头
return new HttpHeaders();
}
public static class WxBaseReq {
}
public static class WxBaseResp {
}
}
问题描述
我们在使用 getHttpHeader() 方法计算签名时,使用的是 t 对象转换为 json 后的字符串,而网络请求中传输过去的是 t 对象,网络框架默认使用 jackson 来序列化对象,而这里我们使用了 fastjson,两者结果不一致,导致最终签名错误。
解决方式
HttpEntity<T> entity = new HttpEntity<>(body, getHttpHeader("POST", apiUrl, body));
将json 字符串通过网络传输,这样就不会受不同 json 框架的影响了。
标签:body,HttpEntity,String,接口,第三方,public,responseEntity,apiUrl,请求 From: https://www.cnblogs.com/strongmore/p/18050078