How to set HttpResponse timeout for Android in Java

后端 未结 10 2197
刺人心
刺人心 2020-11-22 08:02

I have created the following function for checking the connection status:

private void checkConnectionStatus() {
    HttpClient httpClient = new DefaultHttpC         


        
10条回答
  •  梦如初夏
    2020-11-22 08:34

    An option is to use the OkHttp client, from Square.

    Add the library dependency

    In the build.gradle, include this line:

    compile 'com.squareup.okhttp:okhttp:x.x.x'
    

    Where x.x.x is the desired library version.

    Set the client

    For example, if you want to set a timeout of 60 seconds, do this way:

    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
    

    ps: If your minSdkVersion is greater than 8, you can use TimeUnit.MINUTES. So, you can simply use:

    okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
    okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);
    

    For more details about the units, see TimeUnit.

提交回复
热议问题