将JSON发布到服务器会返回空响​​应,但它在Postman中非常有效

时间:2019-03-15 00:03:10

标签: android retrofit2

因此,我的 login.php 脚本在Postman中以原始JSON格式发送请求时工作正常,但是在Android中发送返回空响应,并且尝试将其强制转换为 UserResponse update()方法中,我得到“试图在空对象引用上调用虚拟方法'java.lang.String com.alenpersic.hrvend.Entities.UserResponse.getMessage()'”错误。 postman_request

这是在我的 MainActivity.java

     @Override
public void update(Observable o, Object arg){
    UserResponse response = (UserResponse) arg;
    Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
    if (response.getMessage().equals("Login successful.")){
         Toast.makeText(this, "Prijava uspješna!", Toast.LENGTH_SHORT).show();
         showMachineList();
    }
    else {
        Toast.makeText(this, "Pogrešno korisničko ime i lozinka!", Toast.LENGTH_SHORT).show();
    }
    DataObservable.getInstance().deleteObserver(this);
    showMachineList();
}

public void SignUp (View view){
    User currentUser = new User(usernameEditText.getText().toString(), passwordEditText.getText().toString());
    DataObservable.getInstance().addObserver(this);
    LoginLoader controller = new LoginLoader();
    controller.loadUser(controller.create(), currentUser);
}

WebServiceInterface.java

public interface WebServiceInterface {

@GET("machine/read.php")
Call<MachineResponse> getMachines();

@GET("machine/read_materials.php")
Call<RawMaterialsResponse> getRawMaterials(
        @Query("id") String id
);

@Headers({"Content-Type: application/json"})
@POST("login.php")
Call<LoginResponse> sendUser(
        @Body User user
);

LoginLoader.java

public class LoginLoader extends DataLoader {

public void loadUser(WebServiceInterface webserviceInterface, User user)
{
    Call<LoginResponse> call = webserviceInterface.sendUser(user);
    call.enqueue(this);
}

@Override
public void onResponse(Call call, retrofit2.Response response)
{
    if(response.isSuccessful())
    {
        LoginResponse loginResponse = (LoginResponse) response.body();
        UserResponse data = loginResponse.getData();
        DataObservable.getInstance().notifyObserverWithResponse(data);
    }
    else
    {
        Log.d("MainActivity", response.errorBody().toString() + " " + response.message() + " " + response.raw());
    }
}

LoginResponse.java

public class LoginResponse extends DataResponse {
UserResponse data;

public UserResponse getData(){
    return data;
}

public void setData(UserResponse data){
    this.data = data;
}

User.java

public class User {

@SerializedName("username")
@Expose
private String username;

@SerializedName("password")
@Expose
private String password;

public User(String username, String password) {
    this.username = username;
    this.password = password;
}

public String getUsername() {
    return username;
}

public void setMessage(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

0 个答案:

没有答案