0

以下是我遇到异常(超时)的代码,请提供任何解决方案或教程。在 4.0.4 api 级别设备上使用

 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);

}
4

2 回答 2

0

尝试这个:

HttpConnectionParams.setConnectionTimeout(httpParams,
        TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
于 2012-10-08T13:58:44.383 回答
0

首先你需要了解什么是connectiontimeoutexception:

连接到 HTTP 服务器或等待来自 HttpConnectionManager 的可用连接时超时。

所以这意味着您设备的互联网无法与 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 请求设置更大的超时时间,如下所示:

    公共静态字符串连接(字符串 url)抛出 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;
    

    }

于 2015-04-21T11:02:57.937 回答