2011-04-26 76 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为我改变它。