zoukankan      html  css  js  c++  java
  • Retrofit 2.0使用

    最近在想能不能把之前项目里的网络请求改下

    想通过Retrofit重构下,因为Retrofit完美兼容Rxjava后面会用到Rxjava

    所以

    开个坑写点

    由于网上Retrofit 2.0的架构介绍很详细。所以我这里只提供我遇到的一些问题和解决的方法

    先要依赖

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'

      

    然后,首先要使用Retrofit进行网络请求,你必须建立一个请求接口类 ApiService

    public interface ApiService {
      /*  @GET("service/getIpInfo.php")
        Call<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);*/
    
        @GET("service/getIpInfo.php")
        Observable<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);
    }

    对于上面的代码他分两部分,总的来说

    第一部分@  他采用注解的方式,@表明你所要使用的网络请求。比如我上面用的是Get请求我就@GET 然后后面需要带请求URL的一部分

       然后问题来了,我这个URL要放哪一部分呢。根据我的查证,①你可以全部放一个完整的请求URL地址,这种情况当你在下面建立Retrofit实例类的时候他的.baseUrl(“yourURL”)这个方法里面的URL串就会没有作用;

                                  ②你放地址的一部分,但是要保证建立Retrofit类的.baseUrl(“yourURL”)这个你的URL要和你在上面方法里放一部分地址连接起来他们能成为一个合法的

                                  完整URL地址。而且,你还要满足在使用.baseUrl()方法的时候,你的这个Url参数要是以 / 结尾的地址!

    Ps:对于多个请求参数的写法

      

        @POST("server?")
        Call<GetLoginJson> Login(@Query("command") String login,
                                 @Query("posModel") String posModel,
                                 @Query("posSn") String posSn,
                                 @Query("posMac") String posMac,
                                 @Query("userId") String userId,
                                 @Query("passWord") String passWord,
                                 @Query("Version") String Version};

    第二部分 就是下面接口给外部提供的方法 这个方法也分为两种写法,第一种写法是返回为Call类型回调,我们看代码(注:这个Call回调的方法和上面注释的接口对应)

      

    Retrofit mRetrofit = new Retrofit.Builder() //Retrofit采用典型的Builder模式
            .baseUrl("http://ip.taobao.com")  //接着写入你的URl地址
       .addConverterFactory(GsonConverterFactory.create()) // 新建一个Gson转换器
         .build(); ApiService apiService
    = retrofit.create(ApiService.class); //实例化ApisService 

         Call
    <GetIpInfoResponse> call = apiService.getIpInfo("63.223.108.42");  //调用接口方法

         /**将call接入线程队列中,然后实例化他的callBacl*/
    call.enqueue(
    new Callback<GetIpInfoResponse>() { @Override public void onResponse(Response<GetIpInfoResponse> response, Retrofit retrofit) { GetIpInfoResponse getIpInfoResponse = response.body(); //将返回的数据取出,赋值给返回接收类中(这个下面讲) mTvContent.setText(getIpInfoResponse.data.country); } @Override public void onFailure(Throwable t) { mTvContent.setText(t.getMessage()); } });

    以上代码就是Retrofit的完整的使用流程,看完之后你就会发现我有一个类没有贴出,那就是GetIpInfoResponse

    为什么会有这个类呢,这个类是为了和通信成功后返回了成功值做匹配,返回的数据和他是有关系的,而且他的参数和写法是由返回值决定的。我们来看下代码

    public class GetIpInfoResponse extends BaseResponse {
    public IpInfo data; } public class IpInfo { public String country; public String country_id; public String area; public String area_id; public String ip; }

     我们可以将上面的URl输入到网址看看返回的是什么,http://ip.taobao.com/service/getIpInfo.php ; 但是如果没错应该是{"code":1,"data":"no ip param."},这个没有数据返回应该是和没有在手持机上测试有关系

    所以他的返回类参数就是Json返回的参数,所以这里的data就对应返回关键字为 data 的数据,而这个数据的数据参数如IpInfo这个类,至此Retrofit的使用差不多就这么多;(应该没什么遗漏吧)

    然后下面是和Rxjava一起使用的情况 Retrofit他的使用(注:和Rxjava的时候ApiService为第二个未注释的方法,我这里偷懒了两个都放在一个文件里)

            Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl(“youUrl”)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .build();
                    ApiService apiService = retrofit.create(ApiService.class);
                        apiService.getIpInfo("63.223.108.42")
                            .subscribeOn(Schedulers .io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Subscriber<GetIpInfoResponse>() {
                                @Override
                                public void onCompleted() {
    
                                }
    
                                @Override
                                public void onError(Throwable e) {
                                    mTvContent.setText(e.getMessage());
                                }
    
                                @Override
                                public void onNext(GetIpInfoResponse getIpInfoResponse) {
                                    mTvContent.setText(getIpInfoResponse.data.country);
                                }
                            });

     对于和Rxjava联合使用的好处,那就是我们可以很方便的控制线程开关

    然后使用Retrofit可以使逻辑更加清晰,代码更加简洁和Rxjava联合使用减少了很多秘制缩进的问题

  • 相关阅读:
    c# 时间操作
    JAVA file文件操作
    HttpServletRequest 转换成MultipartHttpServletRequest
    【日常笔记】java spring 注解读取文件
    【日常笔记】mybatis 处理 in 语句的使用
    购物车小程序
    Python中的r+和a+
    markdown基本语法
    markdown箭头的处理
    markdown中如何插入公式
  • 原文地址:https://www.cnblogs.com/fengfenghuifei/p/6029794.html
Copyright © 2011-2022 走看看