我希望有人可以帮助我。
我尝试使用Retrofit 2.0发送带有JSON Body的POST请求。
接口:
public interface Interface {
@POST(/*path*/)
Call<MyResponseObject> sendInt(@Body MyInteger myInt);
}
MyInteger类:
public class MyInteger {
int id;
public MyInteger(int id) {
this.id = id;
}
}
MainActivity的一部分:
private Retrofit mRetrofit = null;
private final Interface mService;
...
...
mRetrofit = new Retrofit.Builder()
.baseUrl(/*URL*/)
.addConverterFactory(GsonConverterFactory.create())
.build();
mService = mRetrofit.create(Interface.class);
电话:
MyInteger id = new MyInteger(0);
mService.sendInt(id).enqueue(new Callback<MyResponseObject>() {
@Override
public void onResponse(Call<MyResponseObject> call, Response<MyResponseObject> response) {/*Log something*/}
@Override
public void onFailure(Call<MyResponseObject> call, Throwable t) {}
});
在我的意见中,它就像这个例子: https://futurestud.io/blog/retrofit-send-objects-in-request-body
但是GsonConverter无法将MyInteger转换为JSON .. 这是日志:
java.lang.IllegalArgumentException: Unable to create @Body converter for class com.??.MyInteger (parameter #1)
for method Interface.sendInt
...
...
Caused by: java.lang.IllegalArgumentException: Could not locate RequestBody converter for class com.??.MyInteger.
Tried:
* retrofit2.BuiltInConverters
* retrofit2.GsonConverterFactory
at retrofit2.Retrofit.nextRequestBodyConverter(Retrofit.java:288)
at retrofit2.Retrofit.requestBodyConverter(Retrofit.java:248)
at retrofit2.RequestFactoryParser.parseParameters(RequestFactoryParser.java:491)
答案 0 :(得分:3)
我遇到了同样的问题。根本原因是我使用的是不兼容的库。
这种组合对我有用:
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.0.0-beta4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.0.0-beta4</version>
</dependency>