Retrofit 上传json

 RequestBody当作参数传递

@PUT(Url)
Call getSubmitCheck(@Body RequestBody requestBody);
RequestBody.create(MediaType.parse("application/json; charset=utf-8"),"json"//json就是要拼的json上传文件

例如

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 call = apiService.add(requestBody);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, retrofit2.Response response) {
                Log.d(getClass().getSimpleName(), "onResponse: ----" + response.body().string());
            }

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

 

 

你可能感兴趣的:(Retrofit 上传json)