我为 Jetty 运行了一个自定义 WebSocketServlet,它将短文本推送通知(对于异步移动设备和 desktop word game )发送到许多平台(Facebook、Vk.com、Mail.ru、Ok.ru 以及 Firebase 和 Amazon 消息传递)使用 Jetty HttpClient 实例:
public class MyServlet extends WebSocketServlet {
private final SslContextFactory mSslFactory = new SslContextFactory();
private final HttpClient mHttpClient = new HttpClient(mSslFactory);
@Override
public void init() throws ServletException {
super.init();
try {
mHttpClient.start();
} catch (Exception ex) {
throw new ServletException(ex);
}
mFcm = new Fcm(mHttpClient); // Firebase
mAdm = new Adm(mHttpClient); // Amazon
mApns = new Apns(mHttpClient); // Apple
mFacebook = new Facebook(mHttpClient);
mMailru = new Mailru(mHttpClient);
mOk = new Ok(mHttpClient);
mVk = new Vk(mHttpClient);
}
这在过去一年中运行得非常好,但自从我最近升级了我的 WAR 文件以使用 Jetty 9.4.14.v20181114 以来,麻烦就开始了 -
public class Facebook {
private final static String APP_ID = "XXXXX";
private final static String APP_SECRET = "XXXXX";
private final static String MESSAGE_URL = "https://graph.facebook.com/%s/notifications?" +
// the app access token is: "app id | app secret"
"access_token=%s%%7C%s" +
"&template=%s";
private final HttpClient mHttpClient;
public Facebook(HttpClient httpClient) {
mHttpClient = httpClient;
}
private final BufferingResponseListener mMessageListener = new BufferingResponseListener() {
@Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
LOG.warn("facebook failure: {}", result.getFailure());
return;
}
try {
// THE jsonStr SUDDENLY CONTAINS PREVIOUS CONTENT!
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
LOG.info("facebook success: {}", jsonStr);
} catch (Exception ex) {
LOG.warn("facebook exception: ", ex);
}
}
};
public void postMessage(int uid, String sid, String body) {
String url = String.format(MESSAGE_URL, sid, APP_ID, APP_SECRET, UrlEncoded.encodeString(body));
mHttpClient.POST(url).send(mMessageListener);
}
}
突然,为成功 HttpClient 调用而调用的 getContentAsString
方法开始传递之前获取的字符串 - 添加到实际结果字符串中。
这可能是什么,是不是有些改变了BufferingResponseListener行为或者可能是一些不明显的 Java 怪癖?
最佳答案
BufferingResponseListener
从来就不是为了跨请求重用而设计的。
只需为每个请求/响应分配一个新的BufferingResponseListener
。
关于java - BufferingResponseListener 和 getContentAsString 追加之前获取的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581559/