I occur error as '@Body parameters cannot be used with form or multi-part encoding' When I send the DTO by FormUrlEncoded naturally when I remove the @FormUrlEncoded than it doesn't occur error But My server construct for FormUrlEncoded
So I want to send the DTO by FormUrlEncoded, What should I do?
RestAPI.java
public interface RestAPI {
interface Join {
@FormUrlEncoded
@POST("/api/users")
Call<Res> createTask(@Body User user);
}
Retrofit RETROFIT = new Retrofit.Builder().baseUrl(Config.ServerUrl).addConverterFactory(GsonConverterFactory.create()).build();
}
public class User {
String username;
String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Res.java
public class Res {
private Boolean response;
private String msg;
public Boolean getResponse() {
return response;
}
public void setResponse(Boolean response) {
this.response = response;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Main.java
user = new User();
user.setUsername("TEST");
user.setPassword("1234");
RestAPI.Join join = RestAPI.RETROFIT.create(RestAPI.Join.class);
Call<Res> resCall = join.createTask(user);
resCall.enqueue(new Callback<Res>() {
@Override
public void onResponse(Call<Res> call, Response<Res> response) {
System.out.println(response.body().getResponse());
}
@Override
public void onFailure(Call<Res> call, Throwable t) {
}
});
答案 0 :(得分:0)
我正在使用像这样的Retrofit:
<强> RetrofitAPI.class 强>
public interface RetrofitAPI
{
@POST("/your/server/doSomething")
Call<ReturnData> doSomething(@Body Param param);
}
<强> ServiceGenerator.class 强>
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit retrofit = null;
private static RetrofitAPI retrofitAPI = null;
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(Constant.BASE_URL).addConverterFactory(GsonConverterFactory.create());
public static Retrofit getRetrofit()
{
if(retrofit == null)
retrofit = builder.client(httpClient.build()).build();
return retrofit;
}
private static <S> S createService(Class<S> serviceClass) {
return getRetrofit().create(serviceClass);
}
public static RetrofitAPI getRetrofitAPI()
{
if(retrofitAPI == null)
retrofitAPI = createService(RetrofitAPI.class);
return retrofitAPI;
}
实际代码
public static void doSomethingViaServer(Param param, Callback<ReturnData> callback)
{
if(param == null)
return;
RetrofitAPI api = ServiceGenerator.getRetrofitAPI();
Call<ReturnData> call = api.doSomething(param);
call.enqueue(callback);
}
希望这有帮助。