在微信开发中我们会经常遇到在处理业务逻辑超过5s的情况,在超时时,微信会重新请求,总共请求三次,这样就会导致一系列的问题,怎样避免这些问题呢?
通过研究发现在微信官方文档清楚写着,如下:
假如服务器无法保证在五秒内处理并回复,必须做出下述回复,这样微信服务器才不会对此作任何处理,并且不会发起重试(这种情况下,可以使用客服消息接口进行异步回复),否则,将出现严重的错误提示。详见下面说明:
1、直接回复空串(指字节长度为0的空字符串,而不是XML结构体中content字段的内容为空) 2、直接回复success
针对微信的官方文字,大家的疑问想必就2个
1、如何直接回复空串或者回复success来避免超时现象呢?
2、如何利用客服接口发送消息?
针对以上2个问题我一一作答
第一个问题很简单可以解决:
即在程序中直接return "";即可,具体实例在下面奉上
第二个问题:
客服接口发送消息想必很多人都会,不细讲,不过下面会奉上实例
然后异步发送可能很多人有疑问,我使用线程的方式实现,做法如下:
public static Object handle(final TextMessage text) {
//超时5s,进行异步发送客服消息
Thread insertDbThread = new Thread(new Runnable() {
@Override
public void run() {
String token=TokenManager.getAccessToken();
ToolCustomerService.connectWeiXinInterface(token,text.getFromUserName(),GetKey.getContent(text));
}
});
insertDbThread.start();
//避免超时时微信重新请求
return "";
}
代码如下:
以被动回复消息为例子
import com.asiainfo.wechat.manager.TokenManager;
import com.asiainfo.wechat.model.message.TextMessage;
import com.asiainfo.whall.tools.GetKey;
import com.asiainfo.whall.tools.ToolCustomerService;
public class TextMessageHandle {
public static Object handle(final TextMessage text) {
//超时5s,进行异步发送客服消息
Thread insertDbThread = new Thread(new Runnable() {
@Override
public void run() {
String token=TokenManager.getAccessToken();
ToolCustomerService.connectWeiXinInterface(token,text.getFromUserName(),GetKey.getContent(text));
}
});
insertDbThread.start();
//避免超时时微信重新请求
return "";
}
}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.log4j.Logger;
public class ToolCustomerService {
private static final Logger LOG = Logger.getLogger(ToolCustomerService.class);
public static void connectWeiXinInterface(String token,String toUser,String content){
URL url;
try {
String action = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token;
String json = "{\"touser\": \""+toUser+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+content+"\"}}";
LOG.info("json:"+json);
url = new URL(action);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));// 传入参数
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
System.out.println("请求返回结果:"+result);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}