Retrofit的进阶之路(一)

    Retrofit的进阶之路(一)关于Service

    Retrofit进阶之路(二)添加请求头和上传图片

    Retrofit和Rxjava的完美结合

 

   Retrofit是Square公司开发的一款针对Android网络请求的框架

   retrofit就是一种框架,它更偏重的是restful思想的实现,本身不具备http标准网络访问基础,它需要依赖okhttp进行网络访问;
   retrofit 是通过注解式定义接口的方式来进行声明,然后再通过实现接口类,调用接口请求数据,使用它能够方便我们可以把API封装成一系列的接口标准,让我们的代码结构更给为清晰;
    在这里强烈建议大家学习retrofit2.0 以上的版本,因为新版和老版在使用上毕竟还是有很多差别的,而且在官网上已经将老版移除了,附上官网地址:
  https://futurestud.io/tutorials/android-basic-authentication-with-retrofit

    这里先主要来讲解下retrofit的网络service

一、引入所需要的依赖

   compile 'io.reactivex:rxjava:1.1.0'
   compile 'io.reactivex:rxandroid:1.1.0'//引入rxjava和rxandroid 主要为后面做铺垫
   compile 'com.squareup.retrofit2:retrofit:2.0.2'
   compile 'com.squareup.retrofit2:converter-gson:2.0.2'
   compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
   compile 'com.google.code.gson:gson:2.6.2'
   compile 'com.jakewharton:butterknife:7.0.1'

二、包含的service包括:get,post,put,delete,下面依次会说明@Path、@Query、@QueryMap、@Body、@Field的用法

        先一起来看个retrofit请求的例子:

    private void getData() {
        //初始化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ReqUrl.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //初始化Service
        CommonService movieService = retrofit.create(CommonService.class);
        //请求数据
        Call<MovieEntity> call = movieService.getTopMovie(0, 10);
        call.enqueue(new Callback<MovieEntity>() {
            @Override
            public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {
                tvContent.setText(response.body().toString());
                Toast.makeText(RetrofitActivity.this, "成功", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFailure(Call<MovieEntity> call, Throwable t) {
                tvContent.setText(t.getMessage());
                Toast.makeText(RetrofitActivity.this, "失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

        service对应如下

    @GET("top250")
    Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
       接下来一起看下其他形式的service

        1、get请求

             1)、一个简单的Get请求

                     例子:http://api.douban.com/v2//Movie

          @GET("Movie")    
          Call<MovieEntity> getItem();

             2)、url中带有参数的

                     例子:http://api.douban.com/v2/Movie/1  

                                http://api.douban.com/v2/Movie/{电影ID}                     

          @GET("Movie/{movieId}")
          Call<MovieEntity> getItem(@Path("movieId") String movieId);
                    或者

                            http://api.douban.com/v2/Movie/1/类型1

                            http://api.douban.com/v2/Movie/{电影ID}/类型1  

         @GET("Movie/{movieId}/{type}")
         Call<Movie> getItem(@Path("movieId") String movieId, @Path("type") String type);

           3)、参数在 url 问号后面的

                例子:http://api.douban.com/v2/Movie?movieId=1  
                           http://api.douban.com/v2/Movie?movieId={电影ID}

          @GET("Movie")
          Call<Movie> getItem(@Query("movieId") String movieId);

               或者

                           http://api.douban.com/v2/Movie?movieId=1&type=类型1  

                           http://api.douban.com/v2/Movie?movieId={电影ID} &type={类型}

          @GET("Movie")
          Call<Movie> getItem(@Query("movieId") String movieId,@Query("type") String type);

           4)、多个参数在url 问号后面且个数不一定,此时用QueryMap

                     例子:http://api.douban.com/v2/Movie?movieId=1.......

                                http://api.douban.com/v2/Movie?movieId={电影ID}

          @GET("Movie")
          Call<Movie> getItem(@QueryMap Map<String, String> map);
  2、post请求

          1)、需要补全 url ,并提交reason参数

                     http://api.douban.com/v2/Comments/1  

                     http://api.douban.com/v2/Comments/{commentId}

          @FormUrlEncoded
          @POST("Comments/{commentId}")
          Call<CommentEntity> reportComment(
              @Path("commentId") String commentId,
              @Field("reason") String reason);

            2)、需要补全url,问号后面需要加入Token,并提交reson参数

                     http://api.douban.com/v2/Comments/1?token=123456 

                     http://api.douban.com/v2/Comments/{commentId}?token={123455}

          @FormUrlEncoded
          @POST("Comments/{commentId}")
          Call<CommentEntity> reportComment(
             @Path("commentId") String commentId,
             @Query("token") String access_token,
             @Field("reason") String reason);
           3)、需要补全url,并且提交多个参数

         @FormUrlEncoded
         @POST("Comments/{commentId}")
         Call<CommentEntity> reportComment(@FieldMap Map<String, String> params);

   3、delete (用的相对少)

          1)、需要补全url的

                    http://api.douban.com/v2/DeleteComments/1  
                    http://api.douban.com/v2/DeleteComments/{commentId}

         @DELETE("Comments/{commentId}")
         Call<ResponseBody> deleteNewsCommentFromAccount(@Path("commentId") String commentId);
           2)、需要补全url ,问号后加token

                  http://api.douban.com/v2/DeleteComments/1?token=123456 
                  http://api.douban.com/v2/DeleteComments/{commentId}?token={123455}

        @DELETE("Comments/{commentId}")
        Call<ResponseBody> deleteCommentFromAccount(
             @Path("commenttId") String commentId,
             @Query("token") String access_token);

   4、put(用的也相对较少)

           http://api.douban.com/v2/Accounts/1  

       @PUT("Accounts/{accountId}")
       Call<ExtrasBean> updateExtras(
         @Path("accountId") String accountId,
         @Query("access_token") String access_token,
         @Body ExtrasBean bean);

      总结:

           @Path:所有在网址中的参数(URL的问号前面),如:
               http://api.douban.com/v2/Comments/{commentId}
           @Query:URL问号后面的参数,如:
               http://api.douban.com/v2/DeleteComments/1?token=123456 
           @QueryMap:相当于多个@Query
           @Field:用于POST请求,提交单个数据
           @Body:相当于多个@Field,以对象的形式提交

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值