httpget - java httprequest timeout
Como definir o tempo limite do HttpResponse para Android em Java (7)
Eu criei a seguinte função para verificar o status da conexão:
private void checkConnectionStatus() {
HttpClient httpClient = new DefaultHttpClient();
try {
String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/"
+ strSessionString + "/ConnectionStatus";
Log.d("phobos", "performing get " + url);
HttpGet method = new HttpGet(new URI(url));
HttpResponse response = httpClient.execute(method);
if (response != null) {
String result = getResponse(response.getEntity());
...
Quando eu desligar o servidor para testar a execução aguarda muito tempo na linha
HttpResponse response = httpClient.execute(method);
Alguém sabe como definir o tempo limite para evitar esperar demais?
Obrigado!
https://code.i-harness.com
No meu exemplo, dois tempos limite estão definidos. O tempo limite de conexão lança "java.net.SocketTimeoutException: Socket não está conectado" e o tempo limite do soquete "java.net.SocketTimeoutException: A operação expirou".
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
Se você quiser definir os parâmetros de qualquer HTTPClient existente (por exemplo, DefaultHttpClient ou AndroidHttpClient), você pode usar a função setParams () .
httpClient.setParams(httpParameters);
Para aqueles que dizem que a resposta de @kuester2000 não funciona, esteja ciente de que as solicitações HTTP tentam primeiro localizar o IP do host com uma solicitação DNS e, em seguida, faz a solicitação HTTP real ao servidor, portanto, também é necessário definir um tempo limite para a solicitação de DNS.
Se o seu código funcionou sem o tempo limite para a solicitação de DNS, é porque você consegue acessar um servidor DNS ou está atingindo o cache DNS do Android. A propósito, você pode limpar esse cache reiniciando o dispositivo.
Esse código estende a resposta original para incluir uma consulta de DNS manual com um tempo limite personalizado:
//Our objective
String sURL = "http://www.google.com/";
int DNSTimeout = 1000;
int HTTPTimeout = 2000;
//Get the IP of the Host
URL url= null;
try {
url = ResolveHostIP(sURL,DNSTimeout);
} catch (MalformedURLException e) {
Log.d("INFO",e.getMessage());
}
if(url==null){
//the DNS lookup timed out or failed.
}
//Build the request parameters
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTPTimeout);
HttpConnectionParams.setSoTimeout(params, HTTPTimeout);
DefaultHttpClient client = new DefaultHttpClient(params);
HttpResponse httpResponse;
String text;
try {
//Execute the request (here it blocks the execution until finished or a timeout)
httpResponse = client.execute(new HttpGet(url.toString()));
} catch (IOException e) {
//If you hit this probably the connection timed out
Log.d("INFO",e.getMessage());
}
//If you get here everything went OK so check response code, body or whatever
Método usado:
//Run the DNS lookup manually to be able to time it out.
public static URL ResolveHostIP (String sURL, int timeout) throws MalformedURLException {
URL url= new URL(sURL);
//Resolve the host IP on a new thread
DNSResolver dnsRes = new DNSResolver(url.getHost());
Thread t = new Thread(dnsRes);
t.start();
//Join the thread for some time
try {
t.join(timeout);
} catch (InterruptedException e) {
Log.d("DEBUG", "DNS lookup interrupted");
return null;
}
//get the IP of the host
InetAddress inetAddr = dnsRes.get();
if(inetAddr==null) {
Log.d("DEBUG", "DNS timed out.");
return null;
}
//rebuild the URL with the IP and return it
Log.d("DEBUG", "DNS solved.");
return new URL(url.getProtocol(),inetAddr.getHostAddress(),url.getPort(),url.getFile());
}
Esta classe é desta postagem do blog . Vá e verifique as observações se você vai usá-lo.
public static class DNSResolver implements Runnable {
private String domain;
private InetAddress inetAddr;
public DNSResolver(String domain) {
this.domain = domain;
}
public void run() {
try {
InetAddress addr = InetAddress.getByName(domain);
set(addr);
} catch (UnknownHostException e) {
}
}
public synchronized void set(InetAddress inetAddr) {
this.inetAddr = inetAddr;
}
public synchronized InetAddress get() {
return inetAddr;
}
}
Se você está usando a biblioteca cliente http de Jakarta, então você pode fazer algo como:
HttpClient client = new HttpClient();
client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(5000));
client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(5000));
GetMethod method = new GetMethod("http://www.yoururl.com");
method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(5000));
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
int statuscode = client.executeMethod(method);
Se você estiver usando o HttpURLConnection
, chame setConnectTimeout()
conforme descrito here :
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
Uma opção é usar o cliente OkHttp , da Square.
Adicione a dependência da biblioteca
No build.gradle, inclua esta linha:
compile 'com.squareup.okhttp:okhttp:x.x.x'
Onde xxx
é a versão da biblioteca desejada.
Definir o cliente
Por exemplo, se você quiser definir um tempo limite de 60 segundos, faça o seguinte:
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
ps: Se o seu minSdkVersion for maior que 8, você pode usar o TimeUnit.MINUTES
. Então, você pode simplesmente usar:
okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);
Para mais detalhes sobre as unidades, consulte TimeUnit .
você pode criar instância HttpClient pelo caminho com Httpclient-android-4.3.5, pode funcionar bem.
SSLContext sslContext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCircularRedirectsAllowed(false).setConnectionRequestTimeout(30*1000).setConnectTimeout(30 * 1000).setMaxRedirects(10).setSocketTimeout(60 * 1000);
CloseableHttpClient hc = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfigBuilder.build()).build();
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParameters,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(httpParameters, true);
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 35 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);