dev dev - 12 days ago 5
Android Question

Http methods deprecated warning in android studio

I am trying to make some http request with parameters. Currently I am using

private List<NameValuePair> mParams = new ArrayList<NameValuePair>();
private DefaultHttpClient mHttpClient;
private HttpPost mHttpPost;


these for making http request and it is working fine. But the problem is android studio is showing deprecated warning for all
these 3 . I tried by using
HttpClientBuilder.create().build();
but android studio cannot import the libraries for
HttpClientBuilder

I tried downloading and adding this jar dependency but still doesn't work. This is my code

mHttpClient = new DefaultHttpClient();
mHttpPost = new HttpPost(url);
mParams.add(new BasicNameValuePair("key", value));
mHttpPost.setEntity(new UrlEncodedFormEntity(mParams));


All these lines are showing deprecated warning, which is the alternative method for this?

Answer

You can use HttpsURLConnection instead of DefaultHttpClient. Also NameValuePair is deprecated, use Uri.Builder and appendQueryParameter to send request parameters.

Try following piece of code:

URL url = new URL("http://myurl.com");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
       .appendQueryParameter("key1", valu1)
       .appendQueryParameter("key2", value2);
String query = builder.build().getEncodedQuery();
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
       new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
connection.connect();