1

我有一个使用设备 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);

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

4

1 回答 1

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;
    }
}
于 2013-02-08T08:10:38.537 回答