Retrofit使用类(get)

来源:互联网 发布:贝多芬第九交响曲 知乎 编辑:程序博客网 时间:2024/05/22 18:56
这几天在网上看了一些网络框架,感觉volley和okhttp简单使用还是比较简单的,一般按照套路来都不会出错,但是使用Retrofit的时候,看网上的使用例子,整个人都懵逼了,都是些什么鬼啊,先是用注解定义接口,然后实例化Retrofit,输入基础网址,然后对Retrofit.create把接口实例化,最后才是网络请求,网络请求还是比较简洁明了的,逼逼了这么多文字,下面是结合代码说明,其实也是为了防止以后自己忘了怎么用,当然,也有封装好的框架给你使用,具体的http://blog.csdn.net/gengqiquan/article/details/52329259         查看。




比如你需要请求数据,get方式,网址:http://apis.juhe.cn/goodbook/catalog?dtype=&key=***************************;定义接口有俩种方式,第一种:
 @GET("{can1}/catalog")
        Call<ResponseBody> responsebody(@Path("can1") String can1, @Query("dtype") String dtype, @Query("key") String key);


@GET是请求方式,{}里面则是需要替换的参数,最后的catalog则是参数名后面接参数,@Path则是替换的参数,@Query则是请求参数,(内是键),后面的跟的则是值




这是一种比较笨重的方式,里面的请求的和传参都已经写死,直接按照如下传参请求数据即可:


 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://apis.juhe.cn/")
                .build();
        QQQ qqq = retrofit.create(QQQ.class);
        Call<ResponseBody> call = qqq.responsebody("goodbook", "json", "*******************************");
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                try {
                    Log.e("---->", response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onFailure(Throwable t) {


            }
        });


按照@GET定义的,将参数传入其中,即可顺利请求到数据。
后面我觉得这个太笨,就稍微改了一下:
 @GET()
        Call<ResponseBody> contributorsBySimpleGetCall(@Url String url, @QueryMap Map<String, String> map);
这个就比较简单了,直接将参数按照键值对的方式一一添加,然后将map参入其中即可:
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://apis.juhe.cn")
                .build();
        GetHubAPI getHubAPI = retrofit.create(GetHubAPI.class);
        Map<String, String> map = new HashMap<>();
        map.put("dtype", "json");
        map.put("key", "*************************");
        Call<ResponseBody> call = getHubAPI.contributorsBySimpleGetCall("/goodbook/catalog", map);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                try {
                    Log.e("response--->", response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("response--->", "错误");
                }
            }


            @Override
            public void onFailure(Throwable t) {


            }
        });


get请求暂时就理解了这些,可能有错误的地方,反正也是写给自己看的
0 0