Reputation: 101
I am using Retrofit 2.0
API: https://newsapi.org/v1/articles?
API interface:
public interface NewsAPI {
// source : the-next-web
// SortBy : latest
@GET("/articles")
Call<Article> articles(
@Query("source") String source,
@Query("apiKey") String apiKey);
}
Fragment:
public class ArticlesFragment extends Fragment {
private NewsAPI newsAPI;
public ArticlesFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.word_list, container, false);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" https://newsapi.org/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
newsAPI = retrofit.create(NewsAPI.class);
loadArticle();
return rootView;
}
public void loadArticle() {
Call<Article> call =
newsAPI.articles("the-next-web", "apiKey");
call.enqueue(new Callback<Article>() {
@Override
public void onResponse(Call<Article> call, Response<Article> response) {
final Article article = response.body();
if (article != null) {
Log.v("this", "YES! response");
}
}
@Override
public void onFailure(Call<Article> call, Throwable t) {
Log.v("this", "NO response ");
}
});
}
Use interceptor v3.4.1 otherwise you will get following error- java.lang.NoSuchMethodError: No virtual method log(Ljava/lang/String;)V in class Lokhttp3/internal/Platform; or its super classes
Configuration for 2.1.0 looks like this:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
Upvotes: 1
Views: 3347
Reputation: 1211
Remove the space in .baseUrl(" https://newsapi.org/v1/")
.
This could be the problem.
Implement HttpLoggingInterceptor
. This way you'll see the GET
you're making. Here is a little help with code.
public static OkHttpClient GetClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
return httpClient.addInterceptor(logging).build();
}
And in retrofit will be like this...
Retrofit retrofit = new Retrofit.Builder()
.client(GetClient())
.baseUrl("https://newsapi.org/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Upvotes: 2
Reputation: 2256
Remove slash from @GET("/articles")
. This makes your final url https://newsapi.org/v1//articles
. Since you've used https://newsapi.org/v1/
to build your retrofit.
Upvotes: 1