JackTurky JackTurky - 5 months ago 64
Android Question

Best practice to get json from url in api 23

I'm using

compileSdk 23
with support library version 23.

I've used httplegacy library (I've copied it into app/libs folder from androidSdk/android-23/optional/org.apache.http.legacy.jar) and in gradle I've put:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}


In order to load that library.

Into my Connection class I've got a method to load an instance of
DefaultHttpClient
in this way:

private static HttpClient getClient(){
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

return httpClient;
}


But Android Studio says me that all
apache.http
classes are deprecated.

What could I use in order to follow best practice?

Answer

There is a reason why this it was deprecated. according to this official page:

This preview removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption

Therefore, you better use HttpURLConnection:

   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();
   }
 }

Another option is to use a network library. I personally uses Fuel on my Kotlin code (but it has Java support) and Http-request on my Java code. Both of the libraries use HttpURLConnection internally.

Here is an example for connecting using Http-Request library:

HttpRequest request = HttpRequest.get("http://google.com");
String body = request.body();
int code = request.code();

And here is an example for connecting using Fuel library:

Fuel.get("http://httpbin.org/get", params).responseString(new Handler<String>() {
    @Override
    public void failure(Request request, Response response, FuelError error) {
        //do something when it is failure
    }

    @Override
    public void success(Request request, Response response, String data) {
        //do something when it is successful
    }
});

Note: Fuel is async library, Http-request is blocking.

Comments