I use ThreadSafeClientConnManager
in my app, and a bunch of other classes like HttpStatus, SSLSocketFactory, PlainSocketFactory, SchemeRegistry, etc. But as of API 22 thery're all being marked as deprecated, and I don't see any clear indication as to what replaced them. The documentation jas says to "Please use openConnection() instead. Please visit this webpage for further details", and that doesn't make it very clear what to do. openConnection()
just points to the URL class, and the webpage link is from 2011 that talks about the differences between the Apache classes and HttpUtrlConnection
. So, does that mean that we're supposed to be useign HttpUrlConnection
class from now on? And if that's the case, I thought that it wasn't thread safe (which is why I was using the ThreadSafeClientConnManager
).
Could someone please clarify this for me?
I asked something like that about half month ago. As it turns out we have to use only openConnection() instead of the old ones.
I think it's a bit early to change your code, as Lollipop is on a few amount of smartphones, but you should change it so you can cut ahead of time. I got a pretty good idea from here how to a connection Using java.net.URLConnection to fire and handle HTTP requests? and also try to search for "httpurlconnection example"
Also about thread safety this, hope it helps
(I tried to post it as a comment but I don't have enough reputation)
Use this HttpUrlConnection as an alternate
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostData(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+=line;
}
}
else {
response="";
throw new HttpException(responseCode+"");
}
} catch (Exception e) {
e.printStackTrace();
}
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(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With