HttpURLConnection 断开连接在 Android 中不起作用
来自 HttpURLConnection
的方法 disconnect 似乎无法正常工作。 如果我执行以下代码:
url = new URL("http:// ...");
connection = (HttpURLConnection) url.openConnection ();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
// Some code
connection.disconnect();
connection.setDoInput(false); // -> IllegalStateException
当我调用方法 setDoInput
时,我得到一个 IllegalStateException
。异常说:
已连接
The method disconnect from HttpURLConnection
seems not to work properly.
If I execute the following code:
url = new URL("http:// ...");
connection = (HttpURLConnection) url.openConnection ();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
// Some code
connection.disconnect();
connection.setDoInput(false); // -> IllegalStateException
I get an IllegalStateException
when I call the method setDoInput
. The exception says:
Already connected
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您正在尝试重用该连接?即在与服务器断开连接后更改请求属性,准备建立另一个连接。
如果是这种情况,则只需创建一个新的 HttpURLConnection 对象即可。
It sounds like you're trying to reuse the connection? i.e. altering the request properties after you've disconnected from the server, ready to make another connection.
If that is the case, then just create a new
HttpURLConnection
object.