Ale*_*ocs 2 java android json retrofit retrofit2
我正在更新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";
}
}
Run Code Online (Sandbox Code Playgroud)
如何改造2?
你可以直接强迫Header application/json(就像你已经完成的那样)并将其作为字符串发送......
..
Call call = myService.postSomething(
RequestBody.create(MediaType.parse("application/json"), jsonObject.toString()));
call.enqueue(...)
Run Code Online (Sandbox Code Playgroud)
然后..
interface MyService {
@GET("/someEndpoint/")
Call<ResponseBody> postSomething(@Body RequestBody params);
}
Run Code Online (Sandbox Code Playgroud)
或者我在这里遗漏了什么?
我修复了下一个代码的问题
public interface LeadApi {
@Headers( "Content-Type: application/json" )
@POST("route")
Call<JsonElement> add(@Body JsonObject body);
}
Run Code Online (Sandbox Code Playgroud)
请注意我使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
注意使用相同版本的 Retrofit 并且它是隐蔽的。它会导致错误!
| 归档时间: |
|
| 查看次数: |
14194 次 |
| 最近记录: |