POST request for Android using HttpUrlConnection, which is "already connected"

I am trying to make a POST call using HttpUrlConnection, but without success. I often get the error "IllegalStateException: already connected." I am not interested in reusing the connection. Please check my code and tell me that I am doing something wrong:

public static final int CONNECTION_TIME_OUT = 10000; public SimpleResponse callPost(String urlTo, Map<String, String> params) { System.setProperty("http.keepAlive", "false"); HttpURLConnection conn = null; SimpleResponse response = new SimpleResponse(0, null); try { URL url = new URL(urlTo); conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setConnectTimeout(CONNECTION_TIME_OUT); conn.setReadTimeout(CONNECTION_TIME_OUT); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(paramsToString(params)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = conn.getInputStream(); String result = StringUtils.fromInputStream(in); response = new SimpleResponse(responseCode, result); in.close(); } else { response = new SimpleResponse(responseCode, null); } } catch (Exception e) { e.printStackTrace(); } if (conn != null) { conn.disconnect(); } return response; } private String paramsToString(Map<String, String> params) { if (params == null || params.isEmpty()) { return ""; } Uri.Builder builder = new Uri.Builder(); for (Map.Entry<String, String> entry : params.entrySet()) { builder.appendQueryParameter(entry.getKey(), entry.getValue()); } return builder.build().getEncodedQuery(); } 

Update:

It works sometimes, and sometimes not! Works on some projects, but not on others!
The same exact code, and each time the same exception: already connected
Why can't I get a new new connection every time?

+7
android post
source share
3 answers

I think your problem is this:

  conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); 

I do not see where postDataBytes declared, but since you are processing the parameters in paramsToString , I assume that they are not relevant.

Now I am not an expert on RFC 2616 (HTTP), but I think that the length of postDataBytes greater than the size of your request, so the server does not disconnect the socket at its end, those URLConnection objects are combined, so when you go to get the connection object, its values have been cleaned for reuse, but the actual connection is still open.

Here is the code I think you should try. If this does not fix your problem, I do not receive a reward for the reputation, but it is still definitely more correct than yours:

 private static final String CHARSET = "ISO-8859-1"; // or try "UTF-8" public SimpleResponse callPost(String urlTo, Map<String, String> params) { // get rid of this... // System.setProperty("http.keepAlive", "false"); HttpURLConnection conn = null; SimpleResponse response = new SimpleResponse(0, null); try { URL url = new URL(urlTo); conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setConnectTimeout(CONNECTION_TIME_OUT); conn.setReadTimeout(CONNECTION_TIME_OUT); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); // ... and get rid of this // conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=" + CHARSET); String content = paramsToString(params); int length = content.getBytes(Charset.forName(CHARSET)).length; conn.setRequestProperty("Content-Length", Integer.toString(length)); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, CHARSET)); writer.write(content); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = conn.getInputStream(); String result = StringUtils.fromInputStream(in); response = new SimpleResponse(responseCode, result); in.close(); } else { response = new SimpleResponse(responseCode, null); } } catch (Exception e) { e.printStackTrace(); } if (conn != null) { conn.disconnect(); } return response; } 

I apologize for any compilation errors. I am useless without an IDE. I proved it as best as possible.

I used Latin-1 encoding. If this is not for you, you can try UTF-8.

Another thing you can try is to discard the length of the content and call

  conn.setChunkedStreamingMode(0); 

And yes, I understand that calling getBytes() and OutputStreamWriter duplicate the same process. You can work on this as soon as you fix this problem.

+3
source

I canโ€™t understand why you are getting an โ€œalready related errorโ€, but here is the code that I use to create POST requests. I close the I / O streams and connection after sending a request that may help you (although I'm not exactly sure)

 try { URL url = new URL(stringURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); connection.setRequestProperty("Accept","application/json"); //connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); //connection.setRequestProperty("Connection", "Keep-Alive"); connection.setReadTimeout(10*1000); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(params[1]); wr.flush(); wr.close(); //Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; response = new StringBuffer(); //Expecting answer of type JSON single line {"json_items":[{"status":"OK","message":"<Message>"}]} while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); System.out.println(response.toString()+"\n"); connection.disconnect(); // close the connection after usage } catch (Exception e){ System.out.println(this.getClass().getSimpleName() + " ERROR - Request failed"); } 
0
source

There are several links online that can help you.

  • Android Httpurlconnection Post and Get Request Tutorial here

  • How to use HttpURLConnection POST data for a web server? here

  • Android POST and GET Request using the HttpURLConnection Tutorial here

0
source

All Articles