Im using HttpUrlConnection to do a http post call with the following code: (I call it from inside an AsyncTask)
public List<String> realizarPostCall(String requestURL, HashMap<String, String> postDataParams) {
URL url;
List<String> response = new ArrayList<>();
try {
url = new URL(requestURL);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(45000);
conn.setConnectTimeout(45000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "ISO-8859-1"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response.add(line);
}
}
} catch (Exception e) {
SincHttp.cancel(true);
e.printStackTrace();
}
if (response.size() == 0) {
response.add(null);
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "ISO-8859-1"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "ISO-8859-1"));
}
return result.toString();
}
Now, when the user closes the activity, im trying to cancel the HttpUrlConnection conn by canceling my AsyncTask and calling conn.Disconnect(). It looks fine, it finishes the activity immediately but i see in the logcat that the connection is still waiting for the response from the server, after the timeout (45 seconds), my logcat show this:
java.net.SocketTimeoutException: failed to connect to /192.168.0.71 (port 8850) after 45000ms
How can i immediately cancel it? i was previously using the Apache Http Library wich is now deprecated and could cancel by calling .abort()