这个问题以前可能被问过,但没有明确的答案。如何在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中这样做吗?


当前回答

我发现当你使用一个复合对象作为@Body参数时,它不能很好地与Retrofit的GSONConverter一起工作(假设你正在使用它)。 你必须使用JsonObject,而不是JsonObject,它添加了NameValueParams而没有详细说明它-你只能看到如果你添加了日志拦截器的另一个依赖项,和其他诡计。

所以我发现解决这个问题的最佳方法是使用RequestBody。 您可以通过一个简单的api调用将对象转换为RequestBody并启动它。 在我的情况下,我转换一个地图:

   val map = HashMap<String, Any>()
        map["orderType"] = orderType
        map["optionType"] = optionType
        map["baseAmount"] = baseAmount.toString()
        map["openSpotRate"] = openSpotRate.toString()
        map["premiumAmount"] = premiumAmount.toString()
        map["premiumAmountAbc"] = premiumAmountAbc.toString()
        map["conversionSpotRate"] = (premiumAmountAbc / premiumAmount).toString()
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSONObject(map).toString())

这就是号召:

 @POST("openUsvDeal")
fun openUsvDeal(
        @Body params: RequestBody,
        @Query("timestamp") timeStamp: Long,
        @Query("appid") appid: String = Constants.APP_ID,
): Call<JsonObject>

其他回答

我们也可以直接使用HashMap<String, Object>来发送主体参数,而不是类 例如

interface Foo {
  @POST("/jayson")
  FooResponse postJson(@Body HashMap<String, Object> body);
}

在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)成功! !

如果不想为每个API调用都创建pojo类,可以使用hashmap。

HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("email","this@gmail.com");
        hashMap.put("password","1234");

然后像这样发送

Call<JsonElement> register(@Body HashMap registerApiPayload);

添加ScalarsConverterFactory.create()方法并传递硬代码

我想比较排射的速度和改装的发送和接收数据,我写在下面的代码(改装部分)

第一个依赖:

dependencies {
     implementation 'com.squareup.retrofit2:retrofit:2.4.0'
     implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
}

然后界面:

 public interface IHttpRequest {

    String BaseUrl="https://example.com/api/";

    @POST("NewContract")
    Call<JsonElement> register(@Body HashMap registerApiPayload);
}

和一个函数来设置参数,张贴数据到服务器(在MainActivity):

private void Retrofit(){

    Retrofit retrofitRequest = new Retrofit.Builder()
            .baseUrl(IHttpRequest.BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // set data to send
    HashMap<String,String> SendData =new HashMap<>();
    SendData.put("token","XYXIUNJHJHJHGJHGJHGRTYTRY");
    SendData.put("contract_type","0");
    SendData.put("StopLess","37000");
    SendData.put("StopProfit","48000");

    final IHttpRequest request=retrofitRequest.create(IHttpRequest.class);

    request.register(SendData).enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
            if (response.isSuccessful()){
                Toast.makeText(getApplicationContext(),response.body().toString(),Toast.LENGTH_LONG).show();
            }
        }

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

        }
    });

}

对我来说,改装比截击更快。