简体   繁体   中英

Retrofit2 Post body as Json

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 ?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM