HttpURLConnection错误:java.net.SocketTimeoutException:连接超时

时间:2012-02-01 10:25:44

标签: java android

我正在使用这样简单的urlconnection:

       url = URL+"getClient&uid="+cl_id;
        URL url = new URL(this.url);
        Log.d("Set++","get_t URL: "+ url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

它工作正常,但有时我得到这个错误:

       error: java.net.SocketTimeoutException: Connection timed out

可能是什么原因?我只有4个客户......所以我不认为服务器超负荷连接。

代码:

    try {
        URL = Settings.BASE_URL + "_interface.php?" +
                "key=" + Settings.KEY +"&app_naam="+Settings.APP_NAAM+ "&action=check&setTime="+c;
        URL url = new URL(URL);
        if(D)Log.e("ChekTreadAanvr+url", URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String response;
        if ((response = rd.readLine()) != null) {
            rd.close();
        }
        if(D) Log.d("WebSaveThread+","DATARESIEVED:  "+response);
        return response;
            } catch (MalformedURLException e) {
        if(D)Log.d("ERR","server chekc failure ++ ");
        return success = false;
    } catch (IOException ioex) {
        if(D)Log.e("ERR", "error: " + ioex.getMessage(), ioex);
        success = false;
    }
    return Boolean.toString(success);

2 个答案:

答案 0 :(得分:2)

您的互联网连接速度可能很弱。您可以使用以下方法增加超时间隔。

httpURLConnection.setConnectTimeout( 6 * 10 * 1000 ); // One Minute

答案 1 :(得分:1)

如果要连接速度特别慢的服务器,可以设置两个超时:setConnectTimeout()setReadTimeout()。名字是相当自我解释的。例如:

            httpURLConnection.setConnectTimeout(60*1000);
            httpURLConnection.setReadTimeout(60*1000);