I have a POJO which I want to send to my backend server using Retrofit 2.0.2. It's a simple LoginRequest
with loginId
and password
. Here's the POJO class:
public class LoginRequest {
private String loginId;
private String password;
public void setLoginId(String loginId) {
this.loginId = loginId;
}
public void setPassword(String password) {
this.password = password;
}
public String getLoginId() {
return loginId;
}
public String getPassword() {
return password;
}
}
The server is expected to get this data as a raw JSON, it would look like this:
{"loginId":"userLoginId","password":"userPassword"}
The initialization of Retrofit is the following:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
As you can see, I use GSON to conversion.
My code for the POST-method is this:
@FormUrlEncoded
@Headers(ServiceHandler.REQUEST_HEADER_TITLE + ServiceHandler.REQUEST_HEADER_VALUE_LOGIN)
@POST(ServiceHandler.ENDPOINT)
Call<LoginResponse> getUser(@Field("loginRequest") String loginRequest);
And I start the connection with this line:
Call<LoginResponse> call = service.getUser(loginRequest);
As I know, the converter is used by Retrofit to convert POJO to JSON for request and JSON to POJO for response. So I thought that it will transform my class into the above JSON format.
However, the backend server's response told me that the format of the field is invalid. When I looked at the OkHTTP logger, I've found that:
05-06 06:27:16.569 14103-14434/my.package.name D/OkHttp: --> POST http://my.web/page.php http/1.1
05-06 06:27:16.569 14103-14434/my.package.name D/OkHttp: Content-Type: application/x-www-form-urlencoded
05-06 06:27:16.569 14103-14434/my.package.name D/OkHttp: Content-Length: 79
05-06 06:27:16.569 14103-14434/my.package.name D/OkHttp: MyHeader: login
05-06 06:27:16.569 14103-14434/my.package.name D/OkHttp: loginRequest=my.package.name.Server.Data.Login.LoginRequest%40189d3779
05-06 06:27:16.569 14103-14434/my.package.name D/OkHttp: --> END POST (79-byte body)
In the 5th row you can see the problem: Retrofit does not serialize my data to JSON before sending the request. All I know about my object that every field inside it is initialized by the setters.
What is the reason? Is my code missing something?