retrofit 如何post json给服务端

  • 需求:
    开发新项目时,拿到接口文档,需要请求消息体是json类型的

可能你这么写过post:

interface NService {
        @FormUrlEncoded
        @POST("alarmclock/add.json")
        Call<ResponseBody> getResult(@FieldMap Map<String, Object> params);
    }
Retrofit retrofit = new Retrofit.Builder().baseUrl(URL).client(client).build();
     NService nService = retrofit.create(NService.class);
     Map<String, Object> params = new HashMap<>();
     params.put("id", "123");
     params.put("name", "ksi");

     Call<ResponseBody> call = nService.getResult(params);
     call.enqueue(new Callback<ResponseBody>() {
         @Override
         public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {

         }

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

         }
     });

这是表单提交,你提交上去的其实是id=123&name=ksi这么个东西。
如果要提交的是json那么自然要改变请求体了

好,有的同学可能会搜索以下问题:怎么查看/更改/添加请求头、请求体、响应体
我的版本是:retrofit2.1.0,2.0以前的做法可能不一样。

首先,在你的build.gradle下面依赖这玩意
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
然后配置client,添加拦截器,第一个拦截器是用于添加请求头的,第二个就是打印日志了

OkHttpClient client = new OkHttpClient().newBuilder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request().newBuilder()
                                .addHeader("creater_oid", "123411") //这里就是添加一个请求头
                                .build();

//                        Buffer buffer = new Buffer();       不依赖logging,用这三行也能打印出请求体
//                        request.body().writeTo(buffer);
//                        Log.d(getClass().getSimpleName(), "intercept: " + buffer.readUtf8());

                        return chain.proceed(request);
                    } //下面是关键代码
                }).addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();

好,我们来干正经事了,json格式的请求,参数注解用@Body

interface ApiService {
        @POST("add.json")
        Call<ResponseBody> add(@Body RequestBody body);
    }
Retrofit retrofit = new Retrofit.Builder().baseUrl(URL).client(client).build();
        ApiService apiService = retrofit.create(ApiService.class);

//new JSONObject里的getMap()方法就是返回一个map,里面包含了你要传给服务器的各个键值对,然后根据接口文档的请求格式,直接拼接上相应的东西就行了
//比如{"data":{这里面是参数}},那就在外面拼上大括号和"data"好了
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                                   "{\"data\":"+new JSONObject(getMap()).toString()+"}");
        Call<ResponseBody> call = apiService.add(requestBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                Log.d(getClass().getSimpleName(), "onResponse: ----" + response.body().string());
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(getClass().getSimpleName(), "onFailure: ------" + t.toString());
            }
        });

OK,大功告成,来看看打印结果吧

QQ截图20160722012756.png

看到第三行了么,那就是自定义添加的请求头,第四行就是json格式的请求体了
<---200 OK下面是响应体。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,293评论 19 139
  • JSON JSON和XML都是需要解析的 JSON是一种轻量级的数据格式,一般用于数据交互服务器返回给客户端的数据...
    JonesCxy阅读 5,860评论 2 10
  • 本文依照 知识共享许可协议(署名-非商业性使用-禁止演绎) 发布。 编写HTTP 服务器与客户端 Vert.x让编...
    半枚荔枝阅读 9,380评论 0 5
  • API定义规范 本规范设计基于如下使用场景: 请求频率不是非常高:如果产品的使用周期内请求频率非常高,建议使用双通...
    有涯逐无涯阅读 7,699评论 0 6
  • 现在做微商还行不行?尤其是现在国家都在大力的倡导个人创业,现在的个体户营业执照的申请已经是零费用,而且在税收上给予...
    南宁进口仓阅读 1,690评论 0 0