【发布时间】:2017-04-17 11:00:18
【问题描述】:
我正在尝试通过 Android 中的 POST 方法将 User 类的对象(使用 Gson-Retrofit)发送到服务器。如果服务器收到任何数据,它会向 App 发送一个 JSON 对象,其中包含 KEY “success”和“message”。但不幸的是,每次服务器都会向 App 发送 {"success":false,"message":"No"}。
我认为从 MainActivity 调用该方法时有问题。为了更好地理解我的所有代码如下:
来自MainActivity.java我调用这个方法:
private void checkUserValidity(User userCredential){
ApiInterface apiInterface = RetrofitApiClient.getClient().create(ApiInterface.class);
Call<ValidityResponse> call = apiInterface.getUserValidity(userCredential);
call.enqueue(new Callback<ValidityResponse>() {
@Override
public void onResponse(Call<ValidityResponse> call, Response<ValidityResponse> response) {
ValidityResponse validity = response.body();
Toast.makeText(getApplicationContext(), validity.getMessage(), Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
我的ApiInterface.java 班级是:
public interface ApiInterface {
@POST("/retrofit_login/login.php")
Call<ValidityResponse> getUserValidity(
@Body User userLoginCredential);
}
RetrofitApiClient.java 类是:
public class RetrofitApiClient {
private static final String BASE_URL = "http://192.168.0.101"; //address of your localhost
private static Retrofit retrofit = null;
private static Gson gson = new GsonBuilder()
.setLenient()
.create();
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
User.java 类是:
public class User {
@SerializedName("user_id")
private String userId;
@SerializedName("password")
private String password;
public User(){}
public void setUserId(String userId) {
this.userId = userId;
}
public void setPassword(String password) {
this.password = password;
}
}
ValidityResponse.java 类是:
public class ValidityResponse {
@SerializedName("success")
boolean successString;
@SerializedName("message")
String messageString;
public boolean isSuccess(){
return successString;
}
public String getMessage() {
return messageString;
}
}
最后服务器端的php代码是:
<?php
if (isset($_POST['user_id']) && isset($_POST['password']))
$json = array('success' => true, 'message' => 'Yes');
else
$json = array('success' => false, 'message' => 'No');
echo json_encode($json);
?>
问题出在哪里?我现在该怎么办? 感谢您的宝贵时间。
【问题讨论】:
-
首先使用 POSTMAN 检查服务是否正常
-
尝试将您的基本网址更改为
localhost。 -
isset($_POST['user_id'])...这就是PHP中json解析的方式...我不知道...显然它总是错误的... -
从我的 App 端发送 {"user_id": "something", "password":"123"}。我的逻辑是:如果“user_id”和“password”字段中有任何数据,它应该发送“yes”否则“no”。如何在 PHP 中检查这个?
-
我如何在 PHP 中检查这个? 你需要学习一些 PHP 基础知识,比如 json 解析......和内容类型(这是 HTTP 协议的基础知识)...... . 然后您可以学习如何阅读文档:$_POST - 使用 application/x-www- 时通过 HTTP POST 方法传递给当前脚本的变量关联数组form-urlencoded 或 multipart/form-data 作为请求中的 HTTP Content-Type。 ... 而改造使用的是 json 默认情况下