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
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;
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.
*/
* 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 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;
}
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("articles?apiKey=" + API_KEY)
Call
@GET("sources")
Call getSources();
}
}
Call
}
}
Step :-2:- Calling class code
Call responseCall = NewsAPI.getNewsAPI().getSources();
No comments:
Post a Comment