Android UnknownHostException:有没有办法设置超时?

2022-09-01 14:49:37

当我连接到我的Web服务以检索数据时,手机有时会断开连接,DNS混乱等。然后我得到一个完全没问题。UnknownHostException

我想做的是在这里查找主机名时设置超时:

 response = httpclient.execute(httpget);

我已经设置了:

HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

但他们似乎不申请.有没有办法在主机查找时设置超时?HostLookUp

编辑
我刚刚发现用户无法在hc-dev邮件列表上修改此帖子中的超时。nslookup

此时,我将不得不从计时器手动抛出超时异常。


答案 1

首先,HttpParams httpParams = new BasicHttpParams() 被剥夺了,请使用这个 HttpURLConnection conn = (HttpURLConnection) url.openConnection();

当您的参数大小大于2mb时,服务器会给出超时响应。

检查您的参数大小,并让我知道。


答案 2

试试这个

public class MyAsync extends AsyncTask<String, Integer, String> {


@Override
protected String doInBackground(String... arg0) {
     HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpClient client=new DefaultHttpClient(httpParameters);
    HttpGet get=new HttpGet(arg0[0]);
    try {
        HttpResponse response=client.execute(get);
        HttpEntity ent=response.getEntity();
        String res=EntityUtils.toString(ent);
        Log.d("Nzm", res);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

}


推荐