Retrofit2 Post body as Json

2019-02-19 22:35发布

问题:

I was updating Retrofit to use Retrofit2 and I already managed to a lot of things GET, POST, PUT...

But i had a request that i have to send a whole JSON I managed to do it in Retrofit 1.9 but in Retrofit2 there is no support for it.

import retrofit.mime.TypedString;

public class TypedJsonString extends TypedString {
    public TypedJsonString(String body) {
        super(body);
    }

    @Override
    public String mimeType() {
        return "application/json";
    }
}

How to make it retrofit2 ?

回答1:

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?



回答2:

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!