我有一個有趣的問題。已建立連接但沒有互聯網的UnknownHostException超時
我有一個應用程序,其中,我試圖說明手機連接到路由器,但該路由器沒有連接到互聯網的情況。
我已經嘗試了建立連接的多種方法,但沒有超時的帳戶爲這種情況。
我已經試過:
HttpParams httpParameters = new BasicHttpParams();
int timeoutSocket = 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutSocket);
我也試過:
HttpURLConnection huc = (HttpURLConnection)serverAddress.openConnection();
huc.setDoOutput(true);
huc.setRequestMethod("PUT"); // For amazon
//huc.setRequestMethod("POST"); // For regular server.
huc.setRequestProperty("Content-Type", "text/plain");
huc.setRequestProperty("Content-Length", String.valueOf(bytes));
huc.setFixedLengthStreamingMode(bytes);
huc.setConnectTimeout(1000); // Establishing connection timeout
huc.setReadTimeout(1000);
但在這兩種情況下,當我執行/獲取輸出流,它需要大約20秒接收一個UnknownHostException錯誤。
我希望在達到這個結論之前減少到最多5秒。
有沒有辦法做到這一點?
乾杯
您能否告訴我應該在哪裏放置這段代碼,與UrlConnection相關? –
你應該能夠把它放在URLConnection之前,即: URL address = new URL(「Your URL」); InetAddress inetAddress = InetAddress.getByName(address.getHost()); URLConnection urlConnection = address.openConnection(); – Dave