使用感想:结合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); }