2011-04-26 63 views
2

我在Android上遇到了HttpClient的這個奇怪的問題。如果我嘗試使用WiFi連接到https網址,則在發送acctual請求之前有一段延遲。如果我通過3G發送請求,延遲不存在。Android上使用Wifi的HttpClient導致延遲(初始請求)

但是,它只出現在Android 2.2和2.3上,如果我運行2.1-update1,它也可以在wifi上正常工作。

但是,在初始請求之後立即發送請求時,它在Wifi上也能正常工作 - 但只是一段時間。然後,它可以追溯到以10秒一個,然後再適當一會兒......

上2.3運行時: 11285毫秒

而且在1.6: 617毫秒

代碼我使用的是嘗試解決這個問題是這樣的 HttpManager和:

public class Main extends Activity { 

Button button; 
TextView text; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    button = (Button) findViewById(R.id.button); 
    button.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      doRequest(); 
     } 

    }); 
} 

private void doRequest() { 
    HttpGet httpget = new HttpGet("https://url_goes_here/"); 

    HttpResponse httpResponse = null; 
    try { 
     ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
     long before = System.currentTimeMillis(); 
     httpResponse = HttpManager.execute(httpget); 
     long after = System.currentTimeMillis(); 

     HttpEntity entity = httpResponse.getEntity(); 
     String response = convertStreamToString(entity.getContent()); 
     Log.i("Test", response); 

     TextView text = (TextView) findViewById(R.id.text); 
     text.setText((String) "Time: " + (after-before) + "\n" + response); 

    } catch (Exception e) { 
     e.printStackTrace(); 
     // Simplified code a bit 
    } 
} 

protected static String convertStreamToString(InputStream is) { 

    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 

其中延遲出現該生產線HttpManager.execute(HTTPGET);這也是我計算MS的線。

有沒有人遇到過這個問題?我覺得這個延遲很煩人,我的用戶也會這樣。仿真器的運行方式與運行2.1-update1的Xperia Mini Pro的運行方式相同,它可以在Wifi上正常運行,運行CyanogenMod 7(2.3)的HTC Desire運行不正常。

回答

1

android中包含的ssl棧存在問題。我也爲此付出了努力。轉到apache home,並獲取org.apache.http java包(我使用v4.1)。將它包含在你的應用程序中並直接使用它的HttpClient,而不是使用內置於Android的HttpClient,並且你的SSL握手延遲問題將得到解決。

+0

不幸的是,這似乎並不奏效。另外,如果這會成爲問題,爲什麼它會在3G上工作,而不是WiFi? :/ – 2011-04-26 19:01:10

+0

嗯......我看到的是,在wifi上,由於連接速度的原因,SSL握手延遲更爲明顯,而3G上的其他延遲問題掩蓋了時間。我在多臺設備上看到了WiFi與3G上的一些非常奇怪且不一致的行爲。值得注意的是,我們在Backflip的os 1.6上完全沒有問題,就像您所描述的那樣。 從你對第一次問題的描述中,你必須重用你的HttpClient,這很好,但它又指出SSL握手是時間接收器,因爲這不需要在每個請求上執行。 – Tyvin 2011-04-26 19:26:48

+0

嗯,沒關係。只是爲了確保我正確添加httpclient.4.1.1.jar,httpcore-4.1.jar和httpmime-4.1.1.jar ...我需要做的唯一事情就是添加它們來構建路徑,對吧? – 2011-04-26 19:32:48

0

在路由器上禁用DNS中繼!它只是爲我工作!

此外,沒有任何版本的httpclient或httpcore爲我改變它。