我正在更新Retrofit以使用Retrofit2,并且我已经设法得到、发布、放置了很多东西.
但是我有一个请求,我必须发送一个完整的JSON,我在Retroeft1.9中成功地做到了这一点,但是在Retrofit2中没有对它的支持。
import retrofit.mime.TypedString;
public class TypedJsonString extends TypedString {
public TypedJsonString(String body) {
super(body);
}
@Override
public String mimeType() {
return "application/json";
}
}如何使它成为retrofit2?
发布于 2016-05-17 19:59:28
您可以将标题强制为application/json (正如您所做的那样),并将其作为字符串发送.
。。
Call call = myService.postSomething(
RequestBody.create(MediaType.parse("application/json"), jsonObject.toString()));
call.enqueue(...)然后..。
interface MyService {
@GET("/someEndpoint/")
Call<ResponseBody> postSomething(@Body RequestBody params);
}还是我在这里漏掉了什么?
发布于 2016-02-12 20:02:11
我用下一段代码解决了这个问题
public interface LeadApi {
@Headers( "Content-Type: application/json" )
@POST("route")
Call<JsonElement> 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);
}
}注意要有相同版本的改装和它的掩护。它会导致错误!
https://stackoverflow.com/questions/35353205
复制相似问题