2012-03-08 65 views
27

當我連接到我的web服務來檢索數據時,手機有時會斷開連接,DNS混亂等等。然後我得到一個UnknownHostException,這非常好。Android UnknownHostException:有沒有辦法設置超時?

我想要做的是設置超時尋找主機這裏的時候:

response = httpclient.execute(httpget); 

我已經設置:

HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection); 
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

,但似乎他們不申請HostLookUp 。有什麼方法可以在主機查找時設置超時時間嗎?

編輯
我剛剛發現用戶不能修改的nslookupin this post on the hc-dev mailing list超時。

我將不得不在手動拋出一個計時器超時異常的那一點。

+0

請給出您的Web服務運行的IP地址,而不是域名。我也面臨同樣的問題。但我的web服務在本地運行在我的機器上。所以,當我給本地主機時,它會引發異常。但它接受我的IP地址。 – 2013-12-17 10:34:02

回答

-1

你應該使用這樣的事情:

/** 
* Check availability of web service 
* 
* @param host Address of host 
* @param seconds Timeout in seconds 
* @return Availability of host 
*/ 
public static boolean checkIfURLExists(String host, int seconds) 
{ 
    HttpURLConnection httpUrlConn; 
    try 
    { 
     httpUrlConn = (HttpURLConnection) new URL(host).openConnection(); 

     // Set timeouts in milliseconds 
     httpUrlConn.setConnectTimeout(seconds * 1000); 
     httpUrlConn.setReadTimeout(seconds * 1000); 

     // Print HTTP status code/message for your information. 
     System.out.println("Response Code: " + httpUrlConn.getResponseCode()); 
     System.out.println("Response Message: " 
       + httpUrlConn.getResponseMessage()); 

     return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK); 
    } 
    catch (Exception e) 
    { 
     System.out.println("Error: " + e.getMessage()); 
     return false; 
    } 
} 
+0

setConnectTimeout和setReadTimeout不適用於DNS解析運行時...這是問題 – weakwire 2012-11-05 09:03:08

0

試試這個

public class MyAsync extends AsyncTask<String, Integer, String> { 


@Override 
protected String doInBackground(String... arg0) { 
    HttpParams httpParameters = new BasicHttpParams(); 
     // Set the timeout in milliseconds until a connection is established. 
     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); 
    HttpClient client=new DefaultHttpClient(httpParameters); 
    HttpGet get=new HttpGet(arg0[0]); 
    try { 
     HttpResponse response=client.execute(get); 
     HttpEntity ent=response.getEntity(); 
     String res=EntityUtils.toString(ent); 
     Log.d("Nzm", res); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return null; 
} 

}

-2

是的,你可以設置超時時間步驟

  1. 轉到eclipse的窗口 - > preferences-> Android-> DDMS並增加ADB連接超時。
+2

-1:weakwire正在談論他的應用中的超時 - 而不是ADB連接。 – sven 2013-12-17 21:06:10

-2

您可以向服務器發送ping請求併爲ping請求設置超時。如果這是真的你有互聯網連接,如果虛假什麼也不做。代碼應該看起來像這樣:

public static boolean connection() throws UnknownHostException, IOException { 
    String ipAddress = "94.103.35.164"; 
    InetAddress inet = InetAddress.getByName(ipAddress); 

    if(inet.isReachable(1000)){ 
     return true; 
    } 
    else { 
     return false; 
    } 
} 

您可以在此示例中更改您的超時時間。我設置了1秒超時。

+0

爲什麼你用空格編輯我的答案=)) – Shockelduck 2013-12-23 09:21:00

0

我發現Volley(我會說替換AsyncTask)庫更容易使用,並且也減少了錯誤。如果你使用凌空,管理超時更容易。然而,關於你的問題,

response = httpclient.execute(httpget); 

與此我假設你正在使用AsyncTask。在httpconnection中也有一個settimeout()的選項,但由於DNS的問題,該選項無法正常工作。所以請嘗試使用runnable()並設置它。我在我的一個項目中使用了這種方法,當時還沒有使用Volley。

希望這會有所幫助。

0
DefaultHttpClient client = new DefaultHttpClient(); 

    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 = 30000; 
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
//  HttpConnectionParams.setHeader("Accept", "application/json"); 

    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data. 
    int timeoutSocket = 30000; 
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

    client.setParams(httpParameters); 
0

它會更好,如果你使用線程的網絡操作,那麼你可以給externally.I曾用這種方法來解決,其中規定超時是不工作的問題超時。

在這種方法中後通信代碼寫入處理程序。我們可以通過發送消息來觸發這個處理程序(我們也可以通過消息傳遞數據)。觸發語句被寫入倒數計時器中,並且在線程中的通信代碼之後。並且在處理程序中寫入必要的代碼以禁止觸發(通過向對象分配新的空處理程序)以便只觸發一個觸發工作。

如果你喜歡這個邏輯,需要更多的解釋。下面

0

請評論你可以嘗試像: -

URLConnection connection = null; 
connection = address.openConnection(); 
post = (HttpsURLConnection) connection; 
post.setSSLSocketFactory(context.getSocketFactory()); 
post.setDoInput(true); 
post.setDoOutput(true); 

// Connecting to a server will fail with a SocketTimeoutException if the timeout  elapses before a connection is established 
post.setConnectTimeout(Const.CONNECTION_TIMEOUT_DELAY); 
post.setRequestMethod("POST"); // throws ProtocolException 


post.setRequestProperty("soapaction",""); 
post.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); 
post.setRequestProperty("Authorization", "Basic " +   Base64.encodeToString(strCredentials.getBytes(), Base64.NO_WRAP)); 
      post.setRequestProperty("Content-Length",   String.valueOf(requestEnvelope.length())); 

//讀取將失敗,SocketTimeoutException如果超時時間之前的數據可用.. post.setReadTimeout(Const.READ_TIMEOUT_DELAY);

0

對我來說,如果我們失去了連接(測試:關閉WiFi),則不使用超時。所以我寫了嘗試下載文件達X次,等待每間Ÿ毫秒的方法試試:

public static byte[] getByteArrayFromURL(String url, int maxTries, int intervalBetweenTries) throws IOException { 

    try { 

     return Utils.getByteArrayFromURL(url); 
    } 
    catch(FileNotFoundException e) { throw e; } 
    catch(IOException e) { 

     if(maxTries > 0) { 

      try { 
       Thread.sleep(intervalBetweenTries); 
       return getByteArrayFromURL(url, maxTries - 1, intervalBetweenTries); 
      } 
      catch (InterruptedException e1) { 

       return getByteArrayFromURL(url, maxTries -1, intervalBetweenTries); 
      } 
     } 
     else { 

      throw e; 
     } 
    } 
} 

下面是下載文件的方法,並拋出的UnknownHostException:

public static byte[] getByteArrayFromURL(String urlString) throws IOException { 

    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    InputStream in = null; 
    try { 

     in = new URL(urlString).openStream(); 
     byte[] byteChunk = new byte[BUFFER_SIZE]; 
     int n; 

     while ((n = in.read(byteChunk)) > 0) { 
      out.write(byteChunk, 0, n); 
     } 
    } 
    finally { 
     if (in != null) { 
      try { in.close(); } 
      catch (IOException e) { e.printStackTrace(); } 
     } 
    } 

    return out.toByteArray(); 
} 

現在,如果您要下載的文件不存在,該方法將立即失敗,否則如果拋出IOException(如UnknownHostException),它將重試,直到「maxTries」,在每次嘗試之間等待「intervalBetweenTries」 。

當然,你必須異步使用它。

0

試試這個,可能會對你有所幫助。

final HttpParams httpParams = new BasicHttpParams() 


HttpConnectionParams.setConnectionTimeout(httpParams, 1000) 


HttpConnectionParams.setSoTimeout(httpParams, 30000) 

HttpClient hc = new DefaultHttpClient(httpParams) 

try 
{ 


HttpGet get = new HttpGet("http://www.google.com") 

    HttpResponse response = hc.execute(get) 

    take your response now. 

}

2

首先的HttpParams的HttpParams =新BasicHttpParams的()被depricated, 使用此HttpURLConnection康恩=(HttpURLConnection類)url.openConnection();

當你的參數大於2MB時,服務器給出超時響應。

檢查您的參數大小,讓我知道。

相關問題