天天看点

Java Retrofit2使用

本文使用eclipse编辑器,gradle依赖jar,如若未配置此环境,请转 Java Eclipse配置gradle编译项目 配置好环境后再查看此文

  1. 在build.gradle文件中添加一下依赖
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
           
  1. 定义java bean,bean中的变量名要与返回的json数据中的key保持一致,否则会匹配不上。
// 1. 定义java bean
    /**
     * Java Bean
     */
    public class Info {
        int error_code; // 状态码
        String reason; // 返回状态文字
        Result result; // 页面URL

        @Override
        public String toString() {
            return "Info [error_code=" + error_code + ", reason=" + reason + ", result=" + result.toString() + "]";
        }
    }

    /**
     * Java Bean
     */
    public class Result {
        String h5url;
        String h5weixin;

        @Override
        public String toString() {
            return "Result [h5url=" + h5url + ", h5weixin=" + h5weixin + "]";
        }
    }
           
  1. 定义接口。
static String url = "http://v.juhe.cn/"; // 请求链接
    static String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
    // 2. 定义接口
    public interface InfoService{
        @GET("wepiao/query")
        Call<Info> getInfo(
                @Query(value = "key")
                String key
        );
    }
           

4.获取Retrofit实例

// 3. 获取实例
        Retrofit retrofit = new Retrofit.Builder()
                // 设置OKHttpClient,如果不设置会提供一个默认的
                .client(new OkHttpClient())
                //设置baseUrl
                .baseUrl(url)
                //添加Gson转换器
                .addConverterFactory(GsonConverterFactory.create())
                .build();
           
  1. 执行retrofit.create方法
// 4. 执行retrofit.create方法
        InfoService infoService = retrofit.create(InfoService.class);
           
  1. 执行同步请求
// 5. 执行请求
        Call<Info> call = infoService.getInfo(KEY);
        Response<Info> response = call.execute();
        
        // 6. 判断是否成功,成功则打印出数据
        if (response.isSuccessful()) {
            Info info = response.body();
            System.out.println(info.toString());
        }
           
  1. 执行异步请求
// 5. 执行请求
        Call<Info> call = infoService.getInfo(KEY);
        call.enqueue(new Callback<RetrofitTest2.Info>() {
            
            public void onResponse(Call<Info> call, Response<Info> response) {
                Info info = response.body();
                System.out.println(info);
            }
            
            public void onFailure(Call<Info> call, Throwable t) {
                System.out.println(t.getMessage());
            }
        });
           

retrofit注解:

方法注解,包含@GET、@POST、@PUT、@DELETE、@PATH、@HEAD、@OPTIONS、@HTTP。

标记注解,包含@FormUrlEncoded、@Multipart、@Streaming。

参数注解,包含@Query,@QueryMap、@Body、@Field,@FieldMap、@Part,@PartMap。

其他注解,@Path、@Header,@Headers、@Url。

几种特殊的注解

@HTTP:可以替代其他方法的任意一种

/**
     * method 表示请的方法,不区分大小写
     * path表示路径
     * hasBody表示是否有请求体
     */
    @HTTP(method = "get", path = "users/{user}", hasBody = false)
    Call<ResponseBody> getFirstBlog(@Path("user") String user);
           

@Url:使用全路径复写baseUrl,适用于非统一baseUrl的场景。

@GET
    Call<ResponseBody> v3(@Url String url);
           

@Streaming:用于下载大文件

@Streaming
    @GET
    Call<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);
           
ResponseBody body = response.body();
    long fileSize = body.contentLength();
    InputStream inputStream = body.byteStream();
           

常用注解

@Path:URL占位符,用于替换和动态更新,相应的参数必须使用相同的字符串被@Path进行注释

@GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId);
    //--> http://baseurl/group/groupId/users

    //等同于:
    @GET
    Call<List<User>> groupListUrl(
          @Url String url
    );
           

@Query,@QueryMap:查询参数,用于GET查询,需要注意的是@QueryMap可以约定是否需要encode

@GET("group/users")
    Call<List<User>> groupList(@Query("id") int groupId);
    //--> http://baseurl/group/users?id=groupId
           
Call<List<News>> getNews((@QueryMap(encoded=true) Map<String, String> options);
           

@Body:用于POST请求体,将实例对象根据转换方式转换为对应的json字符串参数,这个转化方式是GsonConverterFactory定义的。

@POST("add")
     Call<List<User>> addUser(@Body User user);
           

@Field,@FieldMap:Post方式传递简单的键值对,需要添加@FormUrlEncoded表示表单提交Content-Type:application/x-www-form-urlencoded.

@FormUrlEncoded
    @POST("user/edit")
    Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
           

@Part,@PartMap:用于POST文件上传

其中@Part MultipartBody.Part代表文件,@Part("key") RequestBody代表参数

需要添加@Multipart表示支持文件上传的表单,Content-Type: multipart/form-data.

@Multipart
    @POST("upload")
    Call<ResponseBody> upload(@Part("description") RequestBody description, @Part MultipartBody.Part file);
           
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
    // use the FileUtils to get the actual file by uri
    File file = FileUtils.getFile(this, fileUri);

    // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

    // add another part within the multipart request
    String descriptionString = "hello, this is description speaking";
    RequestBody description =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), descriptionString);
           

@Header:header处理,不能被互相覆盖,用于修饰参数

//动态设置Header值
    @GET("user")
    Call<User> getUser(@Header("Authorization") String authorization)
           

等同于

//静态设置Header值
    @Headers("Authorization: authorization")//这里authorization就是上面方法里传进来变量的值
    @GET("widget/list")
    Call<User> getUser()
           

@Headers 用于修饰方法,用于设置多个Header值

@Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"
    })
    @GET("users/{username}")
    Call<User> getUser(@Path("username") String username);