Android Retrofit2 Post请求添加Json类型参数笔记

Android Retrofit2 Post请求添加Json类型参数笔记

一.添加Header

1.添加单独Header

对于某个API所需要添加Header时,可以直接在Service接口上添加@Headers注解:

@Headers({
            "Content-Type: application/json;charset=UTF-8",
            "User-Agent: Retrofit-your-App"})
@GET(ConstantsApi.douban_in_theaters)
Observable<MovieTheatersModel> requestTheatersMovies(@Query("city")String city,
                                                         @Query("count")Integer count,
                                                         @Query("start")Integer start);
2.添加共同Header

如上,我们可以发现,大部分API「”Content-Type: application/json;charset=UTF-8”」都是Header中必须的,那么我们可以直接添加在拦截器中:

new Retrofit.Builder()
           .addConverterFactory(GsonConverterFactory.create())

           .client(new OkHttpClient.Builder()
                   .addInterceptor(new Interceptor() {
                       @Override
                       public Response intercept(Chain chain) throws IOException {
                           Request request = chain.request()
                                   .newBuilder()
                                   .addHeader("Content-Type", "application/json;charset=UTF-8")
                                   .addHeader("header2", "123456")
                                   .addHeader("header3", "123456")
                                   .addHeader("header4", "123456")
                                   .build();
                           return chain.proceed(request);
                       }
                   }).build();

然后你说直接这样每次都add一个匿名的intercept,令人头大的缩进,也太不软件工程了,那就直接封装一个:

public class MyInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request()
                .newBuilder()
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("header2", "123456")
                .addHeader("header3", "123456")
                .addHeader("header4", "123456")
                .build();
        return chain.proceed(request);
    }

}

每次请求需要这些header的时候只需要:

HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
MyInterceptor myInterceptor = new MyInterceptor();

OkHttpClient client = new OkHttpClient()
        .newBuilder()
        .addInterceptor(httpLoggingInterceptor)
        .addInterceptor(myInterceptor)
        .build();//添加自定义Interceptor
movieService = new Retrofit.Builder()   //配合Retrofit
          .baseUrl(ConstantsApi.BASE_DOUBAN)
          .addConverterFactory(GsonConverterFactory.create())
          .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
          .client(client)
          .build()
          .create(DoubanMovieService.class);

二.添加Json类型Body

假定需求Json格式如下:

{
    "param1": "111",
    "param2": "222",
    "data": {
        "param3": "string",
        "param4": "string2"
    }
}
1.创建JsonObject对象
 JSONObject root = new JSONObject();
 JSONObject requestData = new JSONObject();
 try {
     requestData.put("param3", "string");
     requestData.put("param4", "string2");
     root.put("param1", "111");
     root.put("param2", "222");
     root.put("data", requestData);
 } catch (JSONException e) {
     e.printStackTrace();
 }
2.API 接口设置
@POST("api/data?")
Observable<PromotionModel> getResult(@Body RequestBody requestBody);
3.联网请求(包含上述1中代码)
JSONObject root = new JSONObject();
JSONObject requestData = new JSONObject();
try {
    requestData.put("param3", "string");
    requestData.put("param4", "string2");
    root.put("param1", "111");
    root.put("param2", "222");
    root.put("data", requestData);
} catch (JSONException e) {
    e.printStackTrace();
}

RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),root.toString());

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(new Interceptor())
        .addInterceptor(logging)
        .build();
service = new Retrofit.Builder()
        .client(client)
        .baseUrl(Constants.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build()
        .create(Service.class);
return service.getResult(requestBody);
  • 8
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值