在调用.Disconnect()之后,HttpUrlConnection仍然在后台等待超时

时间:2016-06-27 17:27:23

标签: java android

我使用HttpUrlConnection使用以下代码进行http post调用:(我在AsyncTask中调用它)

    public List<String> realizarPostCall(String requestURL, HashMap<String, String> postDataParams) {

    URL url;
    List<String> response = new ArrayList<>();
    try {
        url = new URL(requestURL);

        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(45000);
        conn.setConnectTimeout(45000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "ISO-8859-1"));
        writer.write(getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();
        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response.add(line);
            }
        }
    } catch (Exception e) {
        SincHttp.cancel(true);
        e.printStackTrace();
    }

    if (response.size() == 0) {
        response.add(null);
    }
    return response;
}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "ISO-8859-1"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "ISO-8859-1"));
    }

    return result.toString();
}

现在,当用户关闭活动时,我试图通过取消我的AsyncTask并调用conn.Disconnect()来取消HttpUrlConnection conn。它看起来很好,它立即完成活动,但我在logcat中看到连接仍在等待来自服务器的响应,在超时(45秒)后,我的logcat显示:

java.net.SocketTimeoutException: failed to connect to /192.168.0.71 (port 8850) after 45000ms

我怎样才能立即取消它?我之前使用的是Apache Http Library,现已弃用,可以通过调用.abort()来取消。

0 个答案:

没有答案