Android: java.lang.IllegalStateException: Already connected
Asked Answered
P

4

6

I'm testing a sample of code but its always error at 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:

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.

Promotion answered 19/1, 2014 at 2:57 Comment(4)
Did you close the OutputStreamWriter and InputStreamReader after using them ?Disheveled
yes. and the error has happened before the line of OutputStreamWriter and InputStreamReader being used.Promotion
@downvoter: why is it downvoted? i already read and tried other similar question and none is working that's why i'm posting this.Promotion
Because you didn't post the stack trace?Pergrim
P
2
  1. You must close the input stream after reading it to end of stream.

  2. You should remove the call to connect(). You have it in the wrong place, but it's automatic and doesn't need to be called at all.

  3. You can also remove the line that sets POST. This is implicit in calling setDoOutput(true).

  4. 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.

Pergrim answered 5/7, 2016 at 1:57 Comment(0)
H
1

There is a very good post about http connections here

The bottom line is that for POSTs you only need the following.

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.

Here is the POST code that I use for json posts

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();
}
Hasidism answered 2/12, 2014 at 11:19 Comment(0)
P
0

Move

connection.connect();

after

connection.setRequestMethod("POST");
Psychometrics answered 19/1, 2014 at 3:53 Comment(0)
S
-1

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.

Sandalwood answered 4/12, 2016 at 4:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.