java Retrofit2 Post body 为 Json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35353205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrofit2 Post body as Json
提问by Alexsotocs
I was updating Retrofit to use Retrofit2and I already managed to a lot of things GET, POST, PUT...
我正在更新 Retrofit 以使用Retrofit2,并且我已经设法完成了很多 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.
但是我有一个请求,我必须发送整个 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";
}
}
How to make it retrofit2?
如何使它改造2?
回答by VicVu
You can literally just force the Header to be application/json
(as you've done) and send it as a string...
您可以从字面上强制 Header 成为application/json
(正如您所做的那样)并将其作为字符串发送......
..
..
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?
还是我在这里遗漏了什么?
回答by Alexsotocs
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.
请注意我使用 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);
}
}
Take care to have the same version of Retrofit and it's coverter. It lead to errors!
注意使用相同版本的 Retrofit 并且它是隐蔽的。它会导致错误!