2012-10-08 144 views
0

以下是我收到異常(超時)的代碼,請提供相同的解決方案或教程。使用4.0.4 API級設備上Android連接超時例外

HttpClient client = new DefaultHttpClient(); 

HttpPost request = new HttpPost(url); 

List<NameValuePair> params = new LinkedList<NameValuePair>(); 

> param has some values and a string of bitmap. 

HttpResponse response = client.execute(request); 

StringBuilder receivedData = new StringBuilder(); 

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

String line = null; 

while ((line = reader.readLine()) != null) 
{ 

receivedData.append(line); 

} 
+1

使用的AsyncTask做背景 –

+0

@zala janaksinh所有過程:它不工作,先生對我來說... –

+0

啓動谷歌搜索和搜索有關bgprocee例如,它使用它單曲也親愛的。 –

回答

0

試試這個:

HttpConnectionParams.setConnectionTimeout(httpParams, 
     TIMEOUT_MILLISEC); 
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); 
0

首先,你需要了解什麼是connectiontimeoutexception:

超時而連接到一個HTTP服務器或等待來自HttpConnectionManager的可用連接。

這意味着您的設備的Internet無法與HTTP服務器和請求超時進行連接。你可以做以下兩件事情來避免這種情況:

  1. 檢查使用下面的方法進行的HTTP調用之前激活的Internet連接:

    public static Boolean checkActiveInternet(Context activity) { 
    ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); 
        NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
        if (netInfo != null && netInfo.isConnectedOrConnecting()) { 
         return true; 
        } else if (netInfo != null&& (netInfo.getState() == NetworkInfo.State.DISCONNECTED|| netInfo.getState() == NetworkInfo.State.DISCONNECTING|| netInfo.getState() == NetworkInfo.State.SUSPENDED || netInfo.getState() == NetworkInfo.State.UNKNOWN)) { 
         return false; 
        } else { 
         return false; 
        } 
    

    }

  2. 設置一個對HTTP請求的超時時間如下所示:

    public static String connect(String url)throws IOException {

    HttpGet httpget = new HttpGet(url); 
    HttpResponse response; 
    HttpParams httpParameters = new BasicHttpParams(); 
    int timeoutConnection = 60 * 1000; 
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
    int timeoutSocket = 60 * 1000; 
    
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
    HttpClient httpclient = new DefaultHttpClient(httpParameters); 
    try { 
    
        response = httpclient.execute(httpget); 
    
        HttpEntity entity = response.getEntity(); 
        if (entity != null) { 
         InputStream instream = entity.getContent(); 
         result = convertStreamToString(instream); 
         // instream.close(); 
        } 
    } catch (ClientProtocolException e) { 
        Utilities.showDLog("connect", "ClientProtocolException:-" + e); 
    } catch (IOException e) { 
        Utilities.showDLog("connect", "IOException:-" + e); 
    } 
    return result; 
    

    }