android

android http怎样设置超时时间

小樊
92
2024-11-19 09:27:42
栏目: 编程语言

在Android中,您可以使用HttpURLConnection或者第三方库如OkHttp来设置HTTP请求的超时时间。下面是两种方法的示例:

方法1:使用HttpURLConnection

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://example.com");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000); // 设置连接超时时间为5秒
                    connection.setReadTimeout(5000); // 设置读取数据超时时间为5秒
                    int responseCode = connection.getResponseCode();
                    Log.d("ResponseCode", String.valueOf(responseCode));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

方法2:使用OkHttp

首先,您需要在项目的build.gradle文件中添加OkHttp依赖:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.1'
}

然后,您可以使用以下代码设置超时时间:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS) // 设置连接超时时间为5秒
                .readTimeout(5, TimeUnit.SECONDS) // 设置读取数据超时时间为5秒
                .build();

        Request request = new Request.Builder()
                .url("http://example.com")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    Log.d("ResponseCode", String.valueOf(response.code()));
                } else {
                    Log.d("ResponseCode", String.valueOf(response.code()));
                }
            }
        });
    }
}

请注意,如果您使用OkHttp并希望在后台线程中执行网络请求,请确保您已在AndroidManifest.xml中添加INTERNET权限:

<uses-permission android:name="android.permission.INTERNET" />

0
看了该问题的人还看了