改造2没有回复

时间:2017-01-26 11:22:41

标签: android retrofit2

我正在使用Retrofit 2.0
API:https://newsapi.org/v1/articles
API接口:

public interface NewsAPI {
    // source : the-next-web
    // SortBy : latest
    @GET("/articles")
    Call<Article> articles(
            @Query("source") String source,
            @Query("apiKey") String apiKey);
}

片段:

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 ");

            }
        });
    }

更新

使用拦截器v3.4.1否则会出现以下错误 - java.lang.NoSuchMethodError:类Lokhttp3 / internal / Platform中没有虚拟方法日志(Ljava / lang / String;)V;或其超级课程

2.1.0的配置如下所示:

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'

2 个答案:

答案 0 :(得分:2)

删除.baseUrl(" https://newsapi.org/v1/")中的空格。 这可能是问题所在。

更新

实施HttpLoggingInterceptor。这样您就会看到正在制作的GET。这是对代码的一点帮助。

public static OkHttpClient GetClient(){
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        return  httpClient.addInterceptor(logging).build();
        }

在改造中会像这样......

Retrofit retrofit = new Retrofit.Builder()
                .client(GetClient())
                .baseUrl("https://newsapi.org/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

答案 1 :(得分:1)

@GET("/articles")删除斜杠。这会使您的最终网址为https://newsapi.org/v1//articles。由于您已使用https://newsapi.org/v1/来构建改造。