我正在尝试通过Android中的User
方法将POST
类(使用Gson-Retrofit)的对象发送到服务器。如果服务器接收到任何数据,它将向App发送一个包含KEY“success”和“message”的JSON对象。但不幸的是,每次服务器都会向应用程序发送 {“成功”: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);
?>
问题出在哪里?我现在应该怎么做? 谢谢你的时间。
答案 0 :(得分:1)
问题在于您的PHP代码。试试这个:
<?php
$data = file_get_contents('php://input');
$json_data = json_decode($data , true);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
//code to process data
if ($data == "" || empty($json_data['user_id']) || empty($json_data['password']))
{
$response = array('status' => false, 'message' => 'Invalid Values');
}
else
{
$response = array('status' => true,'message' => 'success');
}
echo json_encode($response);
}
?>