forked from chanjarster/weixin-java-tools
-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
MP_如何调用未支持的接口
chanjarster edited this page Nov 3, 2014
·
1 revision
本项目是由个人兴趣发起的项目,所以有时候会比微信官方开放的api要慢一些,如果急着需要使用某个api的话,可以直接使用WxMpService
的下列3个方法来救急:
String get(String url, String queryParam) throws WxErrorException;
String post(String url, String postData) throws WxErrorException;
public <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException;
这三个方法都带有自动刷新access_token和遇到errcode抛出WxErrorException
的功能,所以使用的时候只需专注于业务实现就行了。
get
和post
方法返回的是String
,也就是微信服务器返回的内容。你可以拿这个String
返回值自己处理。
或者使用比较高级的execute
方法,T
是返回值类型,E
是参数类型,可以参考项目里的mediaUpload
方法:
public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException {
String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType;
return execute(new MediaUploadRequestExecutor(), url, file);
}
public class MediaUploadRequestExecutor implements RequestExecutor<WxMediaUploadResult, File> {
@Override
public WxMediaUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File file) throws WxErrorException, ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(config);
}
if (file != null) {
HttpEntity entity = MultipartEntityBuilder
.create()
.addBinaryBody("media", file)
.build();
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
}
CloseableHttpResponse response = httpclient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return WxMediaUploadResult.fromJson(responseContent);
}
}
String encType = request.getParameter("encrypt_type");
String nonce = request.getParameter("nonce");
String timestamp = request.getParameter("timestamp");
String msgSignature = request.getParameter("msg_signature");
String signature = request.getParameter("signature");
String openid = request.getParameter("openid");
log.info("接收微信请求:[openid=[{}], [openid=[{}],[signature=[{}], encType=[{}], msgSignature=[{}],"
+ " timestamp=[{}], nonce=[{}], requestBody=[{}] ",
appid, openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
// 请求里面没有对应信息。 // if (!this.wxMpService.switchover(appid)) { //appid // throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid)); // }
if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
throw new IllegalArgumentException("非法请求,可能属于伪造的请求!");
}
return ResponseEntity.ok("");