HTTPResonse超时

时间:2013-02-08 06:13:07

标签: android timeout httpresponse

我有一个使用设备WiFi发送请求的方案。在这种情况下,WiFi已连接,但WiFi还未连接到互联网,在这种情况下,我发送HTTP请求,但HTTPResonse的响应在这种情况下非常慢。当设备连接到WiFi并且WiFi连接到Internet时,它可以正常工作。

我需要减少第一个场景代码中的响应时间,以便请求

public String[] doHttpGetWithCode(String url, HashMap<String, String> headerParam) throws Exception {
    String[] result = new String[2];
    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
    int timeoutConnection = 3000;
    int timeoutSocket = 5000;
    HttpParams httpParameters = new BasicHttpParams();
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);




    httpget.addHeader("language", Constants.DEVICE_LANGUAGE);       
    Iterator myIterator = headerParam.keySet().iterator();
    while(myIterator.hasNext()) {
        String key=(String)myIterator.next();
        String value=(String)headerParam.get(key);        
        httpget.addHeader(key, value);

    }       
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    result[0] = response.getStatusLine().getStatusCode()+"";
    result[1] = sb.toString();
    return result;
}

我正在使用没有进一步互联网连接的测试WiFi  在这种情况下,以下代码行需要很长时间

response = httpclient.execute(httpget);

需要减少响应时间 提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

/ **  *检查网络服务的可用性  *  * @param host主机地址  * @param seconds超时秒数  * @return主机的可用性  * /

public static boolean checkIfURLExists(String host, int seconds)
{
    HttpURLConnection httpUrlConn;
    try
    {
        httpUrlConn = (HttpURLConnection) new URL(host).openConnection();

        // Set timeouts in milliseconds
        httpUrlConn.setConnectTimeout(seconds * 1000);
        httpUrlConn.setReadTimeout(seconds * 1000);

        // Print HTTP status code/message for your information.
        System.out.println("Response Code: " + httpUrlConn.getResponseCode());
        System.out.println("Response Message: "
                + httpUrlConn.getResponseMessage());

        return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e)
    {
        System.out.println("Error: " + e.getMessage());
        return false;
    }
}