在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" />