Android:java.lang.IllegalStateException:已连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21212674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: java.lang.IllegalStateException: Already connected
提问by Saint Robson
I'm testing a sample of code but its always error at connection.setDoInput(true);
我正在测试一个代码示例,但它总是在 connection.setDoInput(true);
HttpsURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String urlServer = "https://www.myurl.com/upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead = 0;
int bytesAvailable = 0;
int bufferSize = 0;
byte[] buffer = null;
int maxBufferSize = 1*1024*1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(params[0]));
URL url = new URL(urlServer);
connection = (HttpsURLConnection) url.openConnection();
connection.setConnectTimeout(1000);
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setConnectTimeout(1000);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + params[0] + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
The error log is java.lang.IllegalStateException: Already connected
.
I have tried these but none is working:
错误日志是java.lang.IllegalStateException: Already connected
. 我试过这些,但没有一个工作:
connection.setRequestProperty("Connection", "close");
connection.disconnect();
connection.setConnectTimeout(1000);
EDIT: even when i didn't call connection.connect()
, it's still giving the same error already connected
.
编辑:即使我没有打电话connection.connect()
,它仍然给出同样的错误already connected
。
回答by user3211369
Move
移动
connection.connect();
after
后
connection.setRequestMethod("POST");
回答by Will Calderwood
There is a very good post about http connections here
有一个很好的一篇关于http连接在这里
The bottom line is that for POSTs you only need the following.
最重要的是,对于 POST,您只需要以下内容。
HttpURLConnection connection = (HttpURLConnection) new URL(urlToRead).openConnection();
// setDoOutput(true) implicitly set's the request type to POST
connection.setDoOutput(true);
I'm not sure you need to specify HttpsURLConnection either. You can use HttpURLConnection for connecting to Https sites. Let java do the work for you behind the scenes.
我不确定您也需要指定 HttpsURLConnection 。您可以使用 HttpURLConnection 连接到 Https 站点。让 java 在幕后为您完成工作。
Here is the POST code that I use for json posts
这是我用于 json 帖子的 POST 代码
public static String doPostSync(final String urlToRead, final String content) throws IOException {
final String charset = "UTF-8";
// Create the connection
HttpURLConnection connection = (HttpURLConnection) new URL(urlToRead).openConnection();
// setDoOutput(true) implicitly set's the request type to POST
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-type", "application/json");
// Write to the connection
OutputStream output = connection.getOutputStream();
output.write(content.getBytes(charset));
output.close();
// Check the error stream first, if this is null then there have been no issues with the request
InputStream inputStream = connection.getErrorStream();
if (inputStream == null)
inputStream = connection.getInputStream();
// Read everything from our stream
BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream, charset));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = responseReader.readLine()) != null) {
response.append(inputLine);
}
responseReader.close();
return response.toString();
}
回答by user207421
You must close the input stream after reading it to end of stream.
You should removethe call to
connect()
. You have it in the wrong place, but it's automatic and doesn't need to be called at all.You can also remove the line that sets POST. This is implicit in calling
setDoOutput(true)
.You can also remove most of that crud in the copy loop. Use a fixed size buffer:
while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); }
Do not use a new buffer per read; do not call
available()
; do not pass GO; do not collect $200.
您必须在将输入流读取到流末尾后关闭它。
您应该删除对 的调用
connect()
。你把它放在错误的地方,但它是自动的,根本不需要调用。您还可以删除设置 POST 的行。这在调用
setDoOutput(true)
.您还可以在复制循环中删除大部分 crud。使用固定大小的缓冲区:
while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); }
每次读取不要使用新缓冲区;不要打电话
available()
;不要通过GO;不要收取 200 美元。
回答by Jeffrey Chen
Add
添加
if (connection != null) connection.disconnect();
before
前
connection = (HttpsURLConnection) url.openConnection();
See if problem solved. If yes, it means connection.disconnect()
is not called in your original code. Maybe you put connection.disconnect()
at the end of your try
block, however an exception occurs before it, so it jumps to the catch block and connection.disconnect()
is never called.
看看问题是否解决。如果是,则表示connection.disconnect()
未在您的原始代码中调用。也许你放在块connection.disconnect()
的末尾try
,但是在它之前发生了异常,所以它跳转到 catch 块并且connection.disconnect()
永远不会被调用。