Retrofit2将身体贴为Json
我正在更新Retrofit以使用Retrofit2 ,我已经设法做了很多事情GET,POST,PUT ……
但我有一个请求,我必须发送一个完整的JSON,我设法在Retrofit 1.9中做到这一点但在Retrofit2中没有支持它。
import retrofit.mime.TypedString; public class TypedJsonString extends TypedString { public TypedJsonString(String body) { super(body); } @Override public String mimeType() { return "application/json"; } }
如何改造2 ?
您可以简单地强制将Header作为application/json
(就像您已经完成的那样)并将其作为字符串发送…
..
Call call = myService.postSomething( RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())); call.enqueue(...)
然后..
interface MyService { @GET("/someEndpoint/") Call postSomething(@Body RequestBody params); }
或者我在这里遗漏了什么?
我修复了下一个代码的问题
public interface LeadApi { @Headers( "Content-Type: application/json" ) @POST("route") Call add(@Body JsonObject body); }
注意我使用Gson JsonObject的区别。 在创建适配器时,我使用GSON转换器。
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); } }
注意使用相同版本的Retrofit并且它是变换器。 它会导致错误!