如何强制关闭HTTPUrlConnection中的连接并确保使用openConnection()打开新连接

时间:2014-05-28 14:12:03

标签: android httpurlconnection

我写了一个简单的HTTP客户端来向服务器发送休息请求。有好几次我有一个IllegalStateException: Already connected而且一直坚持下去。此外,我使用相同的网址使用不同的方法(POSTGET)并且它们似乎有冲突:当我发出请求时,它会使用相同的方法打开上一个连接,我可以&找不到改变方法。

如何在请求后确保连接真正断开且openConnection()打开新连接?

修改的 我尝试在System.setProperty("http.keepAlive", "false");之前添加HttpURLConnection conn = null;,但我仍然收到错误。

public class RestClient {


    final static public int HTTP_401_UNAUTHORIZED = 401;
    final static public int HTTP_200_OK = 200;

    static public Map<String, Object> post(String urlStr, NameValuePair[] data, boolean hasInput){

        Map<String, Object> response = new HashMap<String, Object>();

        HttpURLConnection conn = null;
        InputStream is = null;

        try {

            URL url = new URL(urlStr);

            conn = (HttpURLConnection) url.openConnection();            

            if(hasInput) conn.setDoInput(true);
            conn.setDoOutput(true);

            if(data != null){

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getQuery(data));
                writer.flush();
                writer.close();
                os.close();
            }

            int status = conn.getResponseCode();

            if(status==HTTP_200_OK) is = conn.getInputStream();
            else is = conn.getErrorStream();    

            response.put("response_code", conn.getResponseCode());

            response.put("response_content", readIt(is));

            return response;

        } catch (MalformedURLException e) {
            e.printStackTrace();
            response.put("response_code", -1);
            response.put("response_content", e.getMessage());
            return response;
        } catch (IOException e) {           
            e.printStackTrace();
            response.put("response_code", -1);
            response.put("response_content", e.getMessage());
            return response;
        }
        finally {

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } 
            if(conn!=null) conn.disconnect();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用此快速解决方法:

conn.setRequestProperty("Connection", "close");

但我不确定这是否真的能解决你的问题。我可以想象IllegalStateException是由对连接对象的方法调用的错误顺序引起的。

设置此属性会降低性能。