Retrofit2基本使用

2018-03-30  本文已影响0人  吃荷包蛋
导入
compile 'com.squareup.retrofit2:retrofit:2.1.0'
Get请求
1.普通get请求

定义get请求接口

private interface ICategoriesBiz {
        //通过@GET注解标识为get请求,@GET中所填写的value与baseurl组成完整的路径
        @GET("user/get-big-direction")
        Call<RespCategory> getCategories();
}

通过retrofit完成请求

Retrofit retrofit = new Retrofit.Builder()
               .baseUrl(BASE_URL)
               .addConverterFactory(GsonConverterFactory.create())
               .build();

ICategories iCategories = retrofit.create(ICategories.class);
Call<RespCategory> call = iCategories.getCategories();
call.enqueue(new Callback<RespCategory>() {
    @Override
  public void onResponse(Call<RespCategory> call,Response<RespCategory> response) {
                RespCategory respCategory = response.body();
                Log.d(TAG, "onResponse");
  }

    @Override
  public void onFailure(Call<RespCategory> call, Throwable t) {

   }
});

addConverterFactory()有多种选择,如果使用gson需额外导入

compile 'com.squareup.retrofit2:converter-gson:2.2.0'

除了gson以外还有如下选择

Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
2.动态访问

retrofit非常适用于restful url风格的格式,如下

//用于访问zach的信息
http://baseurl/springmvc_users/user/zach
//用于访问low的信息
http://baseurl/springmvc_users/user/low

通过username访问不同用户的数据,这个时候我们需要用到@Path

public interface IUserBiz {
    //通过{username}声明了访问路径,可以把{}理解为占位符
    @GET("{username}")
    Call<User> getUser(@Path("username") String username);  //实际运行中会通过@Path("username")所标注的参数进行替换
}
Call<User> call = userBiz.getUser("zach");
//Call<User> call = userBiz.getUser("low");
call.enqueue(new Callback<User>() {

    @Override
    public void onResponse(Call<User> call, Response<User> response) {
        Log.e(TAG, "getUsePath:" + response.body());
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {

    }
});
3.查询参数

例如下面的url

http://baseurl/users?sortby=username

可以通过@Query注解来完成

public interface IUserBiz {
    @GET("users")
    Call<List<User>> getUsersBySort(@Query("sortby") String sort);
}

然后再在构建过程中传入username即可

Post请求
1.json的上传
public interface IUserBiz {
//通过@Body标注参数对象即可
 @POST("add")
 Call<List<User>> addUser(@Body User user);
}
//构建代码省略
Call<List<User>> call = userBiz.addUser(new User(1001, "jj", "123,", "jj123", "jj@qq.com"));
2.表单方式传递键值对

例如用户登录

public interface IUserLogin {
        //通过@POST标注指明路径,添加@FormUrlEncoded,再通过@Fidld添加参数
        @POST("user/do-login")
        @FormUrlEncoded
        Call<RespLoginModel> login(@Field("login_username") String username, @Field("login_password") String password);
    }
......
Call<RespLoginModel> call = iUserLogin.login("zach", "123456");
......
3.单文件上传

采用@Multipart

public interface IUserBiz
{
    //Multipart可以允许多个Part
    @Multipart
    @POST("register")
    Call<User> registerUser(@Part MultipartBody.Part photo, @Part("username") RequestBody username, @Part("password") RequestBody password);
}
File file = new File(Environment.getExternalStorageDirectory(), "icon.png");
RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/png"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("photos", "icon.png", photoRequestBody);

Call<User> call = userBiz.registerUser(photo, RequestBody.create(null, "abc"), RequestBody.create(null, "123"));
4.多个文件上传

使用@PartMap

public interface IUserBiz 
{
     @Multipart
     @POST("register")
     Call<User> registerUser(@PartMap Map<String, RequestBody> params,  @Part("password") RequestBody password);
}

Map可以put进多个文件,key为String类型,代表上传的key(与服务器接收的key对应),value为RequestBody

File file = new File(Environment.getExternalStorageDirectory(), "messenger_01.png");
RequestBody photo = RequestBody.create(MediaType.parse("image/png", file);
Map<String,RequestBody> photos = new HashMap<>();
photos.put("photos\"; filename=\"icon.png", photo);
photos.put("username",  RequestBody.create(null, "abc"));

Call<User> call = userBiz.registerUser(photos, RequestBody.create(null, "123"));
上一篇下一篇

猜你喜欢

热点阅读