Retrofit2 Post body as Json

只谈情不闲聊 提交于 2019-12-01 10:30:24

You can literally just force the Header to be application/json (as you've done) and send it as a string...

..

Call call = myService.postSomething(
    RequestBody.create(MediaType.parse("application/json"), jsonObject.toString()));
call.enqueue(...)

Then..

interface MyService {
    @GET("/someEndpoint/")
    Call<ResponseBody> postSomething(@Body RequestBody params);
}

Or am I missing something here?

I Fixed the problem with the next code

public interface LeadApi {
    @Headers( "Content-Type: application/json" )
    @POST("route")
    Call<JsonElement> add(@Body JsonObject body);
}

Note the difference I'm Using Gson JsonObject. And in the creation of the adapter i use a GSON converter.

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class APIAdapter {
    public static final String BASE_URL = "BaseURL";

    private static Retrofit restAdapter;
    private static APIAdapter instance;

    protected APIAdapter() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        restAdapter = new Retrofit.Builder().baseUrl(BASE_URL).client(client).addConverterFactory(GsonConverterFactory.create()).build();
    }

    public static APIAdapter getInstance() {
        if (instance == null) {
            instance = new APIAdapter();
        }
        return instance;
    }

    public Object createService(Class className) {
        return restAdapter.create(className);
    }

}

Take care to have the same version of Retrofit and it's coverter. It lead to errors!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!