2017-02-28 76 views
0

我試圖創建一個websocket並動態地重新計算每個發送的消息中的標題。可能嗎?okhttp3 websocket動態標題

我試圖使用攔截器,但只調用一次。

public void run() { 

    // only open a websocket if there aren't websockets already open 
    if (this.webSocket == null || !this.openingWS) { 

     this.openingWS = true; 

     wsBuilder = new OkHttpClient.Builder(); 
     OkHttpClient client = wsBuilder.addInterceptor(this) 
       .readTimeout(0, TimeUnit.MILLISECONDS) 
       .build(); 

     Request request = new Request.Builder() 
        .url("wss://...") 
        .build(); 


     client.newWebSocket(request, this); 

     // Trigger shutdown of the dispatcher's executor so this process can exit cleanly. 
     client.dispatcher().executorService().shutdown(); 
    } 
} 

@Override public void onOpen(WebSocket webSocket, Response response) { 
    this.openingWS = false;  // already open 
    this.webSocket = webSocket; // storing websocket for future usages 
    if (listener != null) listener.onWSOpen(); 
} 

public void sendCommand(String cmd) { 
    System.out.println("SEND " + cmd); 
    if (webSocket != null) webSocket.send(cmd); 
} 

此相同的類被實現攔截器

public Response intercept(Chain chain) throws IOException { 
    Request originalRequest = chain.request(); 

    if (!isSpecial()) return chain.proceed(originalRequest); 

    okhttp3.Request.Builder builder = originalRequest.newBuilder() 
      .addHeader("text", "...") 
      .addHeader("dfds", "..."); 


    Request compressedRequest = builder.build(); 

    return chain.proceed(compressedRequest); 

} 

在標頭中發送將改變每X秒/分鐘的認證碼。 如果無法動態更改標題,處理這種連接的最佳方法是什麼?

謝謝你的幫助。

回答

0

我認爲頭只在您請求連接時才發送,稍後取決於客戶端和服務器之間的幀。

所以,如果你想通知服務器,你已經改變了頭,然後發送消息與你的新頭。或者您可以關閉連接並使用新標題開始一個新連接。

+0

這不提供問題的答案。一旦你有足夠的[聲譽](https://stackoverflow.com/help/whats-reputation),你將可以[對任何帖子發表評論](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [來自評論](/ review/low-quality-posts/17561469) –