Wednesday, August 10, 2016

Android Retrofit Example

Retrofit way for calling android Web service Example
http://square.github.io/retrofit/

Add following line in our Gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'
for Maven use following 
 com.squareup.retrofit2
retrofit 2.1.0 

Step :- 1:- Use following below given code for Retrofit Class implementation in your application
package siddhu.test.com.myapplication.network;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
import siddhu.test.com.myapplication.objects.NewsApiArticleResponse;
import siddhu.test.com.myapplication.objects.NewsApiSourcesResponse;
/**
* Created by admin on 8/5/2016.
*/
public class NewsAPI {
private static final String API_KEY = "xyz";
private static final String BASE_URL = "https://newsapi.org/v1/";
private static NewsAPIInterface newsAPIInterface;
public static NewsAPIInterface getNewsAPI() {
if (newsAPIInterface == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
newsAPIInterface = retrofit.create(NewsAPIInterface.class);
}
return newsAPIInterface;
}
public interface NewsAPIInterface {
@GET("articles?apiKey=" + API_KEY)
Call getArticles(@Query("source") String source, @Query("sortBy") String sortBy);
@GET("sources")
Call getSources();
}
}

Step :-2:- Calling class code

Call responseCall = NewsAPI.getNewsAPI().getSources();

No comments: