2

My Andoird app needs to register a token of the device in order to have push notifications. Up to now, I have always used this code:

final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("http://mysite/registration.php");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.e("token:", token);
Log.e("android_id:", android_id );
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("token", token));
nameValuePairs.add(new BasicNameValuePair("device", android_id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); /***/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost); /***/
String responseBody = EntityUtils.toString(response.getEntity()); /***/

Anyway, Android Studio keeps on telling this code is deprecated and I wish I was not forced to add Apache dependencies. For example, I don't want to have

dependencies {
  compile group: 'org.apache.httpcomponents' , 
  name: 'httpclient-android' , 
  version: '4.3.5.1'
}

in my build.gradle.

So, how can I update my code? In particular, I'm having difficulties in understand how to update the lines with /***/. Thank you for your attention

  • Put this `useLibrary 'org.apache.http.legacy'` in the `android { ... }` part or the `build.gradle` file and worry less ;) – Shark Mar 24 '16 at 10:51
  • @Shark As I said in my question, I wouldn't like to use deprecated classes like this. Isn't there a better and newer solution? – Federica Vecchi Mar 24 '16 at 11:02
  • 1
    https://stackoverflow.com/questions/32949626/android-m-org-apache-http-entity-fileentity-deprecated – CommonsWare Mar 24 '16 at 11:22

2 Answers2

0

If you want to break free from the Apache dependency, you can switch to HttpURLConnection, it's part of Android's Java implementation. Here's a simple GET example from the documentation:

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
  InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  readStream(in);
finally {
  urlConnection.disconnect();
}

Your case is a bit more complicated because you POST data via setEntity(). The following answer explains how to do this with Http(s)URLConnection:

https://stackoverflow.com/a/13486223/6055238

Community
  • 1
  • 1
Chris L
  • 41
  • 2
  • Thanks for your reply but what I need to do is an outer buffer. In particular, I don't really know how to convert those lines with /***/ using **HttpURLConnection** you have mentioned. Would you please write them? – Federica Vecchi Mar 24 '16 at 11:58
  • I am aware of that, please consult the answer I linked above, it does exactly that and even gives you an example of how to convert a List into the output you need. The code you'll have to write is a bit more complicated than what you have now but you'll be able to free yourself from a deprecated dependency in return. – Chris L Mar 24 '16 at 12:18
0

You might also want to try or atleast take a look at android's Volley. There are lots of tutorials of it. Here's a sample code:

RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String s) {
        try{
            JSONArray array = new JSONArray(s.toString());
            //getting response here
            }
        catch(Exception e){
            }

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError volleyError) {
    }
}) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String,String> params = new HashMap<String, String>();
        Log.wtf("PID HERE", pid);
        params.put("token", token);
        params.put("device", android_id);
        return params;
    }
};queue.add(sr);
ansonk163
  • 63
  • 3
fmpsagara
  • 485
  • 5
  • 17