Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using square retrofit library to make http requests

I was using loopj async http library to make http requests, but after making researches about android networking library i found out that retrofit is better than volley, the fastet and the most reliable networking library out there.

I planned to change my codes to be suitable to work with retrofit..

Formerly, i used this method to make HTTP requests :

AsyncHttpClient AHC = new AsyncHttpClient();
        RequestParams param = new RequestParams();
        param.put("arg1", arg1);
        param.put("arg2", arg2);
        AHC.post("http://xxxxx.xxx.xxxx.xxxx", param,
                new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(String content) {
                        // TODO Auto-generated method stub

The content i'm getting is json type.

I read that retrofit uses gson by default.. which is really faster i think.

Formerly i used to fill my inner database in that way :

JSONArray jArray = new JSONArray(content);
for (int i = 0; i < jArray.length(); i++) {
    JSONObject json = jArray.getJSONObject(i);
    TD.CreatePostsTable(
            json.getString("id")}

How these methods will become in retrofit ?

Thanks a lot guys!

like image 606
Fringo Avatar asked Oct 21 '22 04:10

Fringo


1 Answers

Your post method:

@POST("/users/login")
    YOUR_RETURN_TYPE loginUser(@Field("arg1") String arg1,
                   @Field("arg2") String arg1);

And the Retrofit config:

new RestAdapter.Builder()
                .setEndpoint("http://your_url")
                .setLogLevel(RestAdapter.LogLevel.FULL).build();

And I'd recommend this approach to use with Retrofit, using a Singleton :

private Map<String, Object> restInstances = new HashMap<String, Object>();
public <T> T getRescClient(Class<T> clazz) {
    T client = null;

    if ((client = (T) restInstances.get(clazz.getCanonicalName())) != null) {
        return client;
    }

    client = restAdapter.create(clazz);
    restInstances.put(clazz.getCanonicalName(), client);
    return client;
}

And then call this:

 restApiProvider.getRestClient(UserService.class).your_method()

Hope it helps !

like image 186
Leonardo Avatar answered Nov 15 '22 10:11

Leonardo