2016-01-10 38 views
1

我得到的con.getResponseCode以下錯誤()SocketTimeoutException在HttpURLConnection的隨機在getResponseCode

java.net.SocketTimeoutException: failed to connect to example.com (port 80) after 3000ms 
at libcore.io.IoBridge.connectErrno(IoBridge.java:223) 
at libcore.io.IoBridge.connect(IoBridge.java:127) 
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:475) 
at java.net.Socket.connect(Socket.java:861) 
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:152) 
at com.android.okhttp.Connection.connect(Connection.java:101) 
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294) 
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255) 
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206) 
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345) 
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296) 
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503) 

,當它被調用它第一次完美的作品。 但它停止工作後,它可能會在一段時間後隨機開始工作。

public class HTTPLoader { 
    public static String loadContentFromURLGET(String urlString,List<String[]> getVars,Context context){ 
     int retry = 0; 
     HttpURLConnection con=null; 
     BufferedReader in = null; 
     StringBuffer response=null; 
     if (!isConnectingToInternet(context)){ 
      return "{'error':'No Internet connection!'}"; 
     } 
     while (retry++<=RETRY_CNT) { 
      try { 
       String urlParameters = ""; 
       for (String[] var : getVars) { 
        urlParameters += var[0] + "=" + URLEncoder.encode(var[1], "UTF-8") + "&"; 
       } 
       if (urlParameters.length() > 1) { 
        urlParameters = urlParameters.substring(0, urlParameters.length() - 1); 
       } 
       if (urlString.charAt(urlString.length() - 1) != '?') { 
        urlString += "&"; 
       } 
       URL url = new URL(urlString + urlParameters); 
       con = (HttpURLConnection) url.openConnection(); 
       con.setConnectTimeout(3000); 
       con.setRequestMethod("GET"); 
       con.setRequestProperty("User-Agent", USER_AGENT); 
       con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
       con.setDoInput(true); 
       con.setDoOutput(true); 
       int responseCode = con.getResponseCode(); 
       in = new BufferedReader(
         new InputStreamReader(con.getInputStream())); 
       String inputLine; 
       response = new StringBuffer(); 

       while ((inputLine = in.readLine()) != null) { 
        response.append(inputLine); 
       } 
       retry = RETRY_CNT+1; 
       break; 
      } catch (IOException e) { 
       e.printStackTrace(); 
       Log.e(TAG, e.getMessage()); 
      }finally { 
       if (in!=null){ 
        try { 
         in.close(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
       if (con!=null) { 
        con.disconnect(); 
       } 
       in = null; 
       con = null; 
      } 
     } 
     if (response!=null) 
      return new String(response); 
     return "{'error':'No Internet connection!'}"; 
    } 
} 

這loadContentFromURLGET正從IntentService

public class ChatUtil extends IntentService{ 
    protected String loadAllChats(String date){ 
      String response = ""; 
      try { 
       SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
       String email = sharedPreferences.getString(QuickstartPreferences.EMAIL, ""); 

      List<String[]> postVars = new ArrayList<>(); 
      postVars.add(new String[]{"getconversation", "yes"}); 
      postVars.add(new String[]{"user_id", email}); 
      postVars.add(new String[]{"last_date", date}); 
      String urlString = getString(R.string.get_conversation_url); 
      response = HTTPLoader.loadContentFromURLGET(urlString, postVars,getApplicationContext()); 
      Log.i(TAG, response.toString()); 
      JSONObject jsonObject = new JSONObject(response); 
      if (jsonObject.has("error")) { 
       //Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show(); 
       return jsonObject.getString("error"); 
      } 
     }catch (JSONException e) { 
     } 
    } 
protected void onHandleIntent(Intent intent) { 
    String task = intent.getStringExtra(QuickstartPreferences.CURRENT_TASK); 
    Intent nintent; 
    String date = ""; 
String[] arr3 = new NewsDBUtil(getApplicationContext()).getLastChatEntry(null); 
      if (arr3!=null) 
       date = arr3[1]; 
      loadAllChats(date); 
      nintent = new Intent(QuickstartPreferences.LOADING_ALL_CHAT); 
      LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(nintent); 
      } 
} 

嘗試閉合和斷開流中最後塊調用。 但沒有成功。

+0

三秒鐘太短的連接超時。增加它。 – EJP

+0

我也檢查過20000,但它的行爲相似。 – Vijay

+0

確實解決了這個問題? – Daniel

回答

0

你可以把con.getResponseCode(); try ... catch塊之間,如果它拋出SocketTimeoutException異常再拍嘗試,但要確保您延長超時

if (responseCode != 200) { 

      .... 
      ... 

    } catch (final java.net.SocketTimeoutException e) { 
     // connection timed out...let's try again     
    } 

這可能幫助

+1

這裏我的問題是爲什麼它給SocketTimeOutException,即使當我連接到高速互聯網,也沒有問題在服務器端? – Vijay

0

沒有具體ContentLength通過setFixedLengthStreamingMode

我發現一些設備生成不完整的http請求

導致服務器必須等待,直到服務器或客戶機超時

你可以使用Wireshark分析問題

+0

上面發佈的相同代碼工作正常,但它隨機停止工作,並給出了socketTimeout。並且在一段時間後再次開始工作。 – Vijay

+0

是的,隨機的異常也發生在我身上,你嘗試過我的方法嗎? 'HttpUrlConnection'類也有其他奇怪的問題,靜靜地雙重發布,EOFException隨機 – Chidchai

相關問題