HttpURLConnection:java.lang.IllegalStateException:已连接

2023-12-19

我正在尝试使用 HttpURLClient 将一些 POST 数据发送到服务器HttpRestClient类如下所示。执行时

conn.setDoInput(true);

I get

java.lang.IllegalStateException: Already connected

我卸载了该应用程序,但仍然出现相同的错误。

在我见过的所有示例中,之前都调用了 openConnectionsetDoInput。如果,正如它的名字所暗示的那样,openConnection打开一个连接,它不应该在`setDoInput之前使用,对吧?我缺少什么?

也许在执行之前的某个时刻它崩溃了disconnect。难道是这个原因吗?如果是这样,我该如何断开旧连接?

public class HttpRestClient {
static public int post(String urlStr, List<NameValuePair> data){

    HttpURLConnection conn = null;

    try {

        URL url = new URL(urlStr);


        conn = (HttpURLConnection) url.openConnection();

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

        conn.setRequestMethod("POST");

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

        InputStream is = conn.getInputStream();

        String dude = readIt(is);

        return 1;

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return 0;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return 0;
    }
    finally {
        if(conn!=null) conn.disconnect();
    }
}
}

这可能是由于在 IDE 中调试时进行观察所致。看这个答案 https://stackoverflow.com/questions/29906562/illegal-state-exception-already-connected-when-using-httpurlconnection/38072310#38072310。 它发生在我身上并且很难发现。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HttpURLConnection:java.lang.IllegalStateException:已连接 的相关文章

随机推荐