Retrofit2的使用,1分钟入门

使用感想:结合rxjava2使用才厉害


gradle

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

Get请求

定义子地址接口(他的url=baseUrl+子地址接口)

public interface GetFriendListAPI{
    @GET("GetFriendListServlet?user_name=136284008")
    retrofit2.Call<JSONObject> getFriendList();
}
使用(在下面就是伪实例化这个接口,再调用接口内的方法。<>中为你想解析出来的数据,写成javabean也可)

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
GetFriendListAPI ipService = retrofit.create(GetFriendListAPI.class);
retrofit2.Call<JSONObject> call = ipService.getFriendList();
call.enqueue(new Callback<JSONObject>() {
    @Override
    public void onResponse(retrofit2.Call<JSONObject> call, Response<JSONObject> response) {
        
    }

    @Override
    public void onFailure(retrofit2.Call<JSONObject> call, Throwable t) {
    }
});
就搞定了。


如果想动态指定查询条件,也就是添加请求头Header,用@Query(就是等于上面的?user_name=136284008)

public interface GetFriendListAPI{
    @GET("GetFriendListServlet")
    retrofit2.Call<JSONObject> getFriendList(@Query("user_name") String userName);
}
在请求的时候是需要小小修改ipService.getFriendList(),在里面添加一个参数就可以了,如136284008


如果有多个条件,比如不止user_name,还有user_password

public interface GetFriendListAPI{
    @GET("GetFriendListServlet")
    retrofit2.Call<JSONObject> getFriendList(@QueryMap Map<String, String> map);
}
在使用的时候,只需要传一个map进去就可以了


POST请求

如果是一个条件,把上面的query相关修改成Field即可

如果是多个条件,把上面的queryMap相关修改成FieldMap即可


如果是要POST一个json字符串,这里的Object指代的是你想要传的对象,他会自动替你把对象转化成json

public interface GetFriendListAPI{
    @GET("GetFriendListServlet")
    retrofit2.Call<JSONObject> getFriendList(@Body Object o);
}


单个文件上传,比如说上传一个图片,第一个参数就是图片,第二个参数就是RequestBody键值对,在使用的时候只需要分别传入图片文件和后面的键值对即可

public interface GetFriendListAPI{
    @Multipart
    @POST("GetFriendListServlet")
    retrofit2.Call<Object> getFriendList(@Part MultipartBody.Part photo, @Part("description")RequestBody description);
}
传入键值对的做法

RequestBody.create("aaa", "xbh");


多个文件上传

用PartMap注解即可



消息报头Header

单个报头

public interface GetFriendListAPI{
    @GET("GetFriendListServlet")
    @Headers("Accept-Encoding: application/json")
    Call<ResponseBody> getCarType();
}

多个报头

public interface GetFriendListAPI{
    @GET("GetFriendListServlet")
    @Headers({
            "Accept-Encoding: application/json",
            "User-Agent:MoonRetrofit"})
    Call<ResponseBody> getCarType();
}

上面是静态添加报头,下面是动态添加报头(很少会这么做)

public interface GetFriendListAPI{
    @GET("GetFriendListServlet")
    Call<ResponseBody> getCarType(@Header("Location") String location);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值