Home >Java >javaTutorial >How to Set HTTP Response Timeouts in Android Java?

How to Set HTTP Response Timeouts in Android Java?

DDD
DDDOriginal
2025-01-01 02:08:09602browse

How to Set HTTP Response Timeouts in Android Java?

Setting HTTP Response Timeout in Java for Android

To prevent excessive waiting during connection status checks in Android, it's essential to set the HTTP response timeout. This involves adjusting two specific parameters:

  • Connection Timeout: This parameter governs the time window available for establishing a connection to the server. By default, no timeout is applied, but setting a non-zero value ensures that if a connection cannot be established within the specified duration, a java.net.SocketTimeoutException: Socket is not connected exception is thrown.
  • Socket Timeout: This parameter regulates the time allowed for waiting for data after a connection has been established. If no data is received within the specified timeout, a java.net.SocketTimeoutException: The operation timed out exception is thrown.

To implement these timeouts:

// Create HTTP parameters object
HttpParams httpParameters = new BasicHttpParams();

// Set connection timeout (3 seconds)
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

// Set socket timeout (5 seconds)
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

// Create HTTP client with the configured timeout parameters
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

// Execute HTTP request
HttpResponse response = httpClient.execute(httpGet);

If you need to configure timeouts on an existing HTTP client, use the httpClient.setParams(httpParameters) function.

The above is the detailed content of How to Set HTTP Response Timeouts in Android Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn