Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 412
Jayyrus Avatar asked Mar 15 '23 19:03

Jayyrus


2 Answers

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.

like image 69
Yoav Sternberg Avatar answered Mar 28 '23 23:03

Yoav Sternberg


Here is my complete example:

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class JSONParser {

    static InputStream is = null;
    static JSONObject json = null;
    static String output = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List params) {
        URL _url;
        HttpURLConnection urlConnection;

        try {
            _url = new URL(url);
            urlConnection = (HttpURLConnection) _url.openConnection();
        }
        catch (MalformedURLException e) {
            Log.e("JSON Parser", "Error due to a malformed URL " + e.toString());
            return null;
        }
        catch (IOException e) {
            Log.e("JSON Parser", "IO error " + e.toString());
            return null;
        }

        try {
            is = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder total = new StringBuilder(is.available());
            String line;
            while ((line = reader.readLine()) != null) {
                total.append(line).append('\n');
            }
            output = total.toString();
        }
        catch (IOException e) {
            Log.e("JSON Parser", "IO error " + e.toString());
            return null;
        }
        finally{
            urlConnection.disconnect();
        }

        try {
            json = new JSONObject(output);
        }
        catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return json;
    }
}

Given a payload that returns {"content": "hello world"}, use like this:

JSONParser jsonParser = new JSONParser();
JSONObject payload = jsonParser.getJSONFromUrl(
        "http://yourdomain.com/path/to/your/api",
        null);
System.out.println(payload.get("content");

It should print out "hello world" in your console.

like image 28
pkout Avatar answered Mar 28 '23 23:03

pkout