I'm trying to make a POST call using HttpUrlConnection but with no success. I'm getting 'IllegalStateException: already connected' error message frequently. I'm not interested in reusing the connection. Please check my code and tell me if I'm doing anything 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:
Works sometimes, and sometimes doesn't!
Works on some projects, on others doesn't!
The same exact code, and each time the same exception: Already connected
Why I'm not able to get a new fresh connection each time?