2012-10-08 51 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; 
    

    }