Reputation: 2190
I am getting the response body as null while making a POST request. I am passing data in the request body. I am making the call using Retrofit2. I have copied the relevant code snippets can you please help me out with the issue:
//JSON Body:
{
"name" : "Anubhav Arora",
"email" : "[email protected]",
"password" : "anubhavpass123"
}
//Response:
{
"message": "User Registered Successfully !!",
"email": "[email protected]"
}
//End Point:
@POST("registeruser")
Call<UserRegistration> registerUser(@Body User user);
//post method call
private void registerUser(String username, String email, String
password) {
User user = new User(username, email, password);
UserEndPoints apiService = APIClient.getClient()
.create(UserEndPoints.class);
Call<UserRegistration> call = apiService.registerUser(user);
call.enqueue(new Callback<UserRegistration>() {
@Override
public void onResponse(Call<UserRegistration> call, Response<UserRegistration> response) {
Toast.makeText(RegisterActivity.this, response.body().getEmail(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<UserRegistration> call, Throwable t) {
Log.d("TAG", t.toString());
}
});
}
//User Class
public class User {
private String name, email, password;
public User(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
//User Registration Class
public class UserRegistration {
@SerializedName("message")
@Expose
private String message;
@SerializedName("email")
@Expose
private String email;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
//API Client
public class APIClient {
//10.0.2.2
public static final String BASE_URL = "http://10.0.2.2:3000/api/v1/";
private static Retrofit retrofit;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Upvotes: 0
Views: 538
Reputation: 1211
you need to add base url
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(url)
.addConvertorFactory(new GsonConvertorFactory.create());
Retrofit retrofit = builder.build();
UserEndPoints apiService = retrofit.create(UserEndPoints.class);
Call<UserRegistration> call = apiService.registerUser(user);
call.enque ......
Upvotes: 0