With what can I replace http deprecated methods?

Bogdan Daniel picture Bogdan Daniel · May 1, 2015 · Viewed 11.8k times · Source

I was following a tutorial and I got to a point where a lot of the code is deprecated.

ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("age", user.age));

HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParamas.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParamas.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");

try{
    post.setEntity(new UrlEncodedFormEntity(dataToSend));
    client.execute(post);
}catch (Exception e){
    e.printStackTrace();
}

and another POST method that is returning a result

    HttpResponse httpResponse = client.execute(post);

    HttpEntity entity = httpResponse.getEntity();
    String result = EntityUtils.toString(entity);
    JSONObject jObject = new JSONObject(result);

I found that I can replace NameValuePair with

ContentValues values = new ContentValues();
values.put("name", user.name);
values.put("age", user.age + "");

but I have no idea about the others.

Answer

CommonsWare picture CommonsWare · May 2, 2015

I found that I can replace NameValuePair with

Not really.

but I have no idea about the others

The entire HttpClient API that ships with Android itself is deprecated. The solution is to use a different HTTP client:

With respect to the tutorial, either:

  • Use tutorials that do not use a deprecated HTTP API, or
  • Port the tutorial to use Apache's repackaged HttpClient for Android, or
  • Ignore the deprecation warnings