当我尝试从服务器获取数据时出现Retrofit错误

时间:2018-02-06 19:57:02

标签: android gson retrofit retrofit2

我做了注册功能并且工作正常但是当我想从服务器获取数据时我遇到了这个问题。

这是我的改装课程

public class ApiClient {

private static final String BASE_URL = "http://10.0.2.2/LOGIN/";
public static Retrofit retrofit;

public static Retrofit getApiClient() {

    if (retrofit == null){
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

    return retrofit;
}
}

这是我的界面

public interface AccountInterface {

 @FormUrlEncoded
 @POST("Register.php")
 Call<String> registerUser(@Field("username") String username,  @Field("password") String password, @Field("name") String name);

 @FormUrlEncoded
 @POST("index.php")
 Call<LoginResponse> loginUser(@Field("username") String username, @Field("password") String password);

}

LoginResponse Class

public class LoginResponse {

User user;

public LoginResponse(User user) {
    this.user = user;
}

public LoginResponse() {
}

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
 }
}

用户类

public class User {
private int user_id;
private String name;
private String password;
private String username;


public User(int id, String name, String password, String username) {
    this.user_id = id;
    this.name = name;
    this.password = password;
    this.username = username;
}

public String getUsername() {
    return username;
}

public int getId() {
    return user_id;
}

public void setId(int id) {
    this.user_id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}


public String getPassword() {
    return password;
}

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

这是我怎么称呼它

 public void saveData(View view) {

    RegisterInterface service = ApiClient.getApiClient().create(RegisterInterface.class);
    Call<LoginResponse> login = service.loginUser(username.getText().toString(),password.getText().toString());

    login.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {

            Log.i(TAG, "onResponse: call  "+ response.body().getUser().getUsername()); 

        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
            Log.i(TAG, "onFailure: "+ t.toString());
        }
    });

}

index.php文件

include_once("db.php");
include_once("LoginResponse.php");
include_once("User.php");

$username = $_POST["username"];
$password = $_POST["password"];

$statment = mysqli_prepare($con, "SELECT * FROM users WHERE username =? AND password = ?");

mysqli_stmt_bind_param($statment,"ss", $username, $password);
mysqli_stmt_execute($statment) or die( mysqli_stmt_error($statment) );

mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment,$userID,$name,$username,$password);

while(mysqli_stmt_fetch($statment)){

  $user = new User($userID,$name,$password,$username);
  $response = new LoginResponse($user);

}

 echo json_encode($response);
}

这是使用邮递员的结果

{"user":{"user_id":20,"name":"user1","password":"123123","username":"username1"}}

这是错误

  

java.lang.IllegalStateException:预期为BEGIN_OBJECT但在第1行第1行为STRING

我想在页面中显示用户数据。 我该如何解决这个问题? 谢谢你的帮助

2 个答案:

答案 0 :(得分:0)

将您的用户类创建为:

public class User {

@SerializedName("user_id")
@Expose
private Integer userId;
@SerializedName("name")
@Expose
private String name;
@SerializedName("password")
@Expose
private String password;
@SerializedName("username")
@Expose
private String username;

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

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

public String getUsername() {
return username;
}

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

}

答案 1 :(得分:0)

问题在于您只返回字典json。它通过改造被解释为String。如果您希望它返回一个对象,您应该在json中添加另一个级别,例如{{"user_id":20,"name":"user1","password":"123123","username":"username1"}}

此外,如果您创建了一个名为LoginResponse的类并将用户包装在其中,则会更好。然后你将你的json改成那个类的模型。像这样:

public class LoginResponse {

    User user;

    public LoginResponse(User user) {
        this.user = user;
    }

    public LoginResponse() {
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

{"user":{"user_id":20,"name":"user1","password":"123123","username":"username1"}}

当然,这会改变您调用改造的方式,而不是通过LoginResponse调用用户。