我为Jetty运行了一个自定义WebSocketServlet,它向多个平台(Facebook,Vk.com,Mail.ru,Ok.ru以及Firebase和Amazon)发送了短文本推送通知(用于异步移动设备和desktop word game)消息)使用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
方法开始传递字符串,这些字符串是先前获取的- prepended 到实际结果字符串。
这可能是什么,是BufferingResponseListener行为的改变还是Java的非显而易见的怪癖?
答案 0 :(得分:2)
BufferingResponseListener
从未打算在请求之间可重复使用。
只需为每个请求/响应分配一个新的BufferingResponseListener
。