代码之家  ›  专栏  ›  技术社区  ›  Alexander Farber

BufferingResponseListener和getContentAsString追加先前获取的内容

  •  0
  • Alexander Farber  · 技术社区  · 6 年前

    desktop word game )使用Jetty HttpClient实例连接到许多平台(Facebook、Vk.com、Mail.ru、Ok.ru以及Firebase和Amazon messaging):

    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);
        }
    }
    

    getContentAsString 为成功调用HttpClient而调用的方法开始传递先前获取的字符串- 预先准备好的 到实际结果字符串。

    请问是什么,是不是换了 BufferingResponseListener 行为还是一些不明显的Java怪癖?

    1 回复  |  直到 6 年前
        1
  •  2
  •   sbordet    6 年前

    BufferingResponseListener

    只需分配一个新的 对于每个请求/响应。