这个问题以前可能被问过,但没有明确的答案。如何在Retrofit请求的主体中发布原始的整个JSON ?

在这里看到类似的问题。或者这个答案是正确的,它必须是表单url编码并作为一个字段传递?我真的希望不是,因为我要连接的服务只是希望在文章正文中有原始JSON。它们不是用来为JSON数据寻找特定字段的。

I just want to clarify this with the restperts once and for all. One person answered not to use Retrofit. The other was not certain of the syntax. Another thinks yes it can be done but only if its form url-encoded and placed in a field (that's not acceptable in my case). No, I can't re-code all the services for my Android client. And yes, it's very common in major projects to post raw JSON instead of passing over JSON content as field property values. Let's get it right and move on. Can someone point to the documentation or example that shows how this is done? Or provide a valid reason why it can/should not be done.

更新:有一件事我可以百分之百确定。你可以在谷歌的Volley中做到这一点。这是与生俱来的。我们可以在Retrofit中这样做吗?


当前回答

经过如此多的努力,发现基本的区别是您需要发送JsonObject而不是JsonObject作为参数。

其他回答

是的,我知道很晚了,但有人可能会从中受益。

使用Retrofit2:

我昨晚从Volley迁移到Retrofit2时遇到了这个问题(正如OP所述,这是用JsonObjectRequest构建到Volley中的),尽管Jake的答案是Retrofit1.9的正确答案,但Retrofit2没有TypedString。

我的情况下需要发送一个地图<字符串,对象>,可以包含一些空值,转换为JSONObject(不会飞@FieldMap,也不特殊字符,一些得到转换),所以遵循@ b规范提示,并由Square声明:

可以使用@Body注释指定对象作为HTTP请求主体。 对象还将使用Retrofit实例上指定的转换器进行转换。如果没有添加转换器,则只能使用RequestBody。

这是一个使用RequestBody和ResponseBody的选项:

在你的接口中使用@Body和RequestBody

public interface ServiceApi
{
    @POST("prefix/user/{login}")
    Call<ResponseBody> login(@Path("login") String postfix, @Body RequestBody params);  
}

在你的调用点创建一个RequestBody,声明它是MediaType,并使用JSONObject将你的Map转换为正确的格式:

Map<String, Object> jsonParams = new ArrayMap<>();
//put something inside the map, could be null
jsonParams.put("code", some_code);

RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),(new JSONObject(jsonParams)).toString());
//serviceCaller is the interface initialized with retrofit.create...
Call<ResponseBody> response = serviceCaller.login("loginpostfix", body);
      
response.enqueue(new Callback<ResponseBody>()
    {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> rawResponse)
        {
            try
            {
             //get your response....
              Log.d(TAG, "RetroFit2.0 :RetroGetLogin: " + rawResponse.body().string());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable throwable)
        {
        // other stuff...
        }
    });

上面的一个优雅的Kotlin版本,允许在应用程序的其余代码中从JSON转换中抽象参数:

interface ServiceApi {

    @POST("/api/login")
    fun jsonLogin(@Body params: RequestBody): Deferred<LoginResult>

}

class ServiceApiUsingClass {

//ServiceApi init

    fun login(username: String, password: String) =
            serviceApi.jsonLogin(createJsonRequestBody(
                "username" to username, "password" to password))

    private fun createJsonRequestBody(vararg params: Pair<String, String>) =
            RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), 
                JSONObject(mapOf(*params)).toString())
}

在Retrofit中需要发送原始json的东西。

1)确保添加以下标题,并删除任何其他重复的标题。因为,在Retrofit的官方文件中他们特别提到了-

注意,头文件不会相互覆盖。所有带有 相同的名字将包含在请求中。

@Headers({"Content-Type: application/json"})

2) a.如果你正在使用一个转换器工厂,你可以传递你的json作为一个字符串,JSONObject, JSONObject,甚至一个POJO。也检查过,有ScalarConverterFactory是没有必要的,只有GsonConverterFactory可以做这项工作。

@POST("/urlPath")
@FormUrlEncoded
Call<Response> myApi(@Header("Authorization") String auth, @Header("KEY") String key, 
                     @Body JsonObject/POJO/String requestBody);

2) b.如果你没有使用任何转换器工厂,那么你必须使用okhttp3的RequestBody,因为Retrofit的文档说-

属性上指定的转换器也将对对象进行转换 改造实例。如果没有添加转换器,则只能添加RequestBody 使用。

RequestBody requestBody=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),jsonString);

@POST("/urlPath")
@FormUrlEncoded
Call<Response> myApi(@Header("Authorization") String auth, @Header("KEY") String key, 
                 @Body RequestBody requestBody);

3)成功! !

1)——添加依赖关系

 compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

2)创建Api Handler类

    public class ApiHandler {


  public static final String BASE_URL = "URL";  

    private static Webservices apiService;

    public static Webservices getApiService() {

        if (apiService == null) {

           Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();
            Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(gson)).baseUrl(BASE_URL).build();

            apiService = retrofit.create(Webservices.class);
            return apiService;
        } else {
            return apiService;
        }
    }


}

3)从Json模式2 pojo制作bean类

还记得 -目标语言:Java -源类型:JSON 注释风格:Gson -select包含getter和setter -你也可以选择允许附加属性

http://www.jsonschema2pojo.org/

4)建立API调用接口

    public interface Webservices {

@POST("ApiUrlpath")
    Call<ResponseBean> ApiName(@Body JsonObject jsonBody);

}

如果你有一个表单数据参数,那么在下面添加

@Headers("Content-Type: application/x-www-form-urlencoded")

其他方式的表单数据参数检查此链接

5)make JsonObject作为参数传递给body

 private JsonObject ApiJsonMap() {

    JsonObject gsonObject = new JsonObject();
    try {
        JSONObject jsonObj_ = new JSONObject();
        jsonObj_.put("key", "value");
        jsonObj_.put("key", "value");
        jsonObj_.put("key", "value");


        JsonParser jsonParser = new JsonParser();
        gsonObject = (JsonObject) jsonParser.parse(jsonObj_.toString());

        //print parameter
        Log.e("MY gson.JSON:  ", "AS PARAMETER  " + gsonObject);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return gsonObject;
}

6)像这样调用Api

private void ApiCallMethod() {
    try {
        if (CommonUtils.isConnectingToInternet(MyActivity.this)) {
            final ProgressDialog dialog;
            dialog = new ProgressDialog(MyActivity.this);
            dialog.setMessage("Loading...");
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();

            Call<ResponseBean> registerCall = ApiHandler.getApiService().ApiName(ApiJsonMap());
            registerCall.enqueue(new retrofit2.Callback<ResponseBean>() {
                @Override
                public void onResponse(Call<ResponseBean> registerCall, retrofit2.Response<ResponseBean> response) {

                    try {
                        //print respone
                        Log.e(" Full json gson => ", new Gson().toJson(response));
                        JSONObject jsonObj = new JSONObject(new Gson().toJson(response).toString());
                        Log.e(" responce => ", jsonObj.getJSONObject("body").toString());

                        if (response.isSuccessful()) {

                            dialog.dismiss();
                            int success = response.body().getSuccess();
                            if (success == 1) {



                            } else if (success == 0) {



                            }  
                        } else {
                            dialog.dismiss();


                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                        try {
                            Log.e("Tag", "error=" + e.toString());

                            dialog.dismiss();
                        } catch (Resources.NotFoundException e1) {
                            e1.printStackTrace();
                        }

                    }
                }

                @Override
                public void onFailure(Call<ResponseBean> call, Throwable t) {
                    try {
                        Log.e("Tag", "error" + t.toString());

                        dialog.dismiss();
                    } catch (Resources.NotFoundException e) {
                        e.printStackTrace();
                    }
                }

            });

        } else {
            Log.e("Tag", "error= Alert no internet");


        }
    } catch (Resources.NotFoundException e) {
        e.printStackTrace();
    }
}

为了更清楚地说明这里给出的答案,下面是如何使用扩展函数。这仅适用于使用Kotlin的情况

如果你正在使用com.squareup.okhttp3:okhttp:4.0.1,旧的创建MediaType和RequestBody对象的方法已经被弃用,不能在Kotlin中使用。

如果您希望使用扩展函数从字符串中获取MediaType对象和ResponseBody对象,首先将以下行添加到您希望在其中使用它们的类中。

import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody

现在可以通过这种方式直接获取MediaType对象

val mediaType = "application/json; charset=utf-8".toMediaType()

要获得RequestBody的对象,首先要将您想要发送的JSONObject转换为字符串。您必须将mediaType对象传递给它。

val requestBody = myJSONObject.toString().toRequestBody(mediaType)

这是我在当前版本的2.6.2中工作的地方,

首先,我们需要添加一个Scalars Converter到我们的Gradle依赖项列表中,它负责将java.lang.String对象转换为文本/纯请求体,

implementation'com.squareup.retrofit2:converter-scalars:2.6.2'

然后,我们需要将一个转换器工厂传递给我们的Retrofit构建器。它稍后将告诉Retrofit如何转换传递给服务的@Body参数。

private val retrofitBuilder: Retrofit.Builder by lazy {
    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
}

注:在我的改造建设者我有两个转换器Gson和 标量,你可以使用他们,但发送Json的主体,我们需要 focus Scalars,所以如果你不需要Gson删除它

然后用String体参数对服务进行翻新。

@Headers("Content-Type: application/json")
@POST("users")
fun saveUser(@Body   user: String): Response<MyResponse>

然后创建JSON主体

val user = JsonObject()
 user.addProperty("id", 001)
 user.addProperty("name", "Name")

呼叫您的服务

RetrofitService.myApi.saveUser(user.toString())