Android http超时选项的测试

 

  • Android http超时选项的测试

  •  

  • Android通过HttpConnectionParams类为http参数设置提供了两个超时的设置选项,分别是setSoTimeout和setConnectionTimeout。初看一眼Android官方给的文档对这个两个方法的具体含义有一种不理解不够清楚的感觉,所以决定通过测试的方式来看看到底在什么情况下这两个参数会起作用。

    经过测试可以发现,setConnectionTimeout设置了建立连接的超时,这是针对TCP的三次握手而言的,如果在指定时间内无法和http服务器建立TCP连接,就会抛出ConnectionTimeoutException。setSoTimeout则设置的是TCP保活时间,在建立了连接之后的指定时间内没有收到服务器发来的相应的数据包,则抛出SocketTimeoutException.

    一、测试代码

    复制代码

    private String urlString;

    private int timeout1,timeout2;

    MyAsyncTask(String url,int timeout1,int timeout2){

    urlString=url;

    this.timeout1=timeout1;

    this.timeout2=timeout2;

    }

    @Override

    protected String doInBackground(String... params) {

    httpget(urlString,timeout1,timeout2);

    return "test";

    }

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    new MyAsyncTask("http://www.xiaonei.com:1234",3000,5000).execute("start");

    new MyAsyncTask("http://www.baidu.com",3000,5000).execute("start");

    }

    private void httpget(String Url,int timeout1,int timeout2) {

    Log.v("httpget", "httpget start timeout1 is "+timeout1+"timeout2 is "+timeout2);

    int timeoutConnection = timeout1; // until connection is established

    int timeoutSocket = timeout2; // timeout for waiting for data

    HttpParams httpParameters = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(httpParameters,

    timeoutConnection);

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    HttpGet postRequest = new HttpGet(Url);

    HttpResponse httpResp = null;

    try {

    httpResp = httpClient.execute(postRequest);

    } catch (ClientProtocolException e) {

    Log.v("Main", "clinet protocol exception");

    return;

    }catch (SocketTimeoutException e) {

    // TODO: handle exception

    Log.v("Main", "socket timeout"+timeout2);

    return;

    }catch (ConnectTimeoutException e) {

    // TODO: handle exception

    Log.v("Main", "connection timeout"+timeout1);

    return;

    }

    catch (IOException e) {

    Log.v("Main", "io exception");

    return;

    }

    }

你可能感兴趣的:(android)