无法使用改型从API获取数据

时间:2019-10-20 17:33:03

标签: php android api retrofit2

我已经用PHP实现了一个简单的API,并使用邮递员对其进行了测试,并且效果很好。但是,当我使用改造来获取数据却无法正常工作时,它只会对排队的请求执行onFailure()方法。

改造界面

public interface UserAPI {

@POST("createUser.php")
Call<User> createUser(@Body User user);
}

改装请求

  Call<User> call = userAPI.createUser(user);

  call.enqueue(new Callback<User>() {

    @Override
    public void onResponse(Call<User> call, Response<User> response) {

      startActivity(new Intent(RegisterActivity.this, MainActivity.class));

    }

    @Override
     public void onFailure(Call<User> call, Throwable t) {
       Toast.makeText(RegisterActivity.this,t.getCause(),Toast.LENGTH_SHORT).show();
    }

    });

用户类别

public class User {
 public int userId;
 public String username;
 public String realName;
 public String phoneNumber;
 public String email;
 public String password;
}

createUser.php实现

require_once('./serviceDB.php');
require_once('./User.php');

header("Content-type: application/json; charset=utf-8");


if($_SERVER['REQUEST_METHOD'] == 'POST') {

  $data = json_decode(file_get_contents('php://input'), true);

  $username = $data['user']['username'];
  $mobile = $data['user']['mobile'];
  $email = $data['user']['email'];
  $password = $data['user']['password'];

  $user = new User();

  $user->setUsername($username);
  $user->setEmail($email);
  $user->setMobile($mobile);
  $user->setPassword($password);
  serviceDB::createUser($user)

和API中的createUser方法

public static function createUser($user){
$query = 'Insert Into Users (Username, Email,Mobile, Password) VALUES (:username, :email, :mobile,:password)';
    $params = array(':username' => $user->username , ':email' => $user->email, ':mobile' => $user->mobile,':password' => $user->password);
$id = ServiceDB::Query($query, $params);
return $id;

}

0 个答案:

没有答案