在进行retrofit2 post请求时,响应正文为null

时间:2017-09-07 19:18:44

标签: android retrofit2

我在发出POST请求时将响应正文设置为null。我在请求正文中传递数据。我正在使用Retrofit2进行通话。我已经复制了相关的代码片段,请你帮我解决一下这个问题:

// JSON Body:

{
  "name" : "Anubhav Arora",
  "email" : "anubhavarora02@gmail.com",
  "password" : "anubhavpass123"
}

//回复:

{
  "message": "User Registered Successfully !!",
  "email": "anubhavarora02@gmail.com"
}

//终点:

@POST("registeruser")
Call<UserRegistration> registerUser(@Body User user);

//发布方法调用

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());
        }
    });
}

//用户类

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;
}

}

//用户注册类

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客户端

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;
}
}

1 个答案:

答案 0 :(得分:0)

您需要添加基本网址

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 ......