Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit POST: JSON object does't send to PHP server

I'm trying to send an object of User class (using Gson-Retrofit) to server via POST method from Android. If server receive any data, it will send a JSON object to App which contains KEY "success" and "message". But unfortunately each and every time server sends {"success":false,"message":"No"} to App.

I think there are something wrong when I call the method from MainActivity. For more understanding all of my codes are given below:

From MainActivity.java I call this method:

    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());
        }
    });
}

My ApiInterface.java class is:

public interface ApiInterface {
    @POST("/retrofit_login/login.php")
    Call<ValidityResponse> getUserValidity(
        @Body User userLoginCredential);
}
        

RetrofitApiClient.java class is:

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 class is:

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 class is:

public class ValidityResponse {

    @SerializedName("success")
    boolean successString;
    @SerializedName("message")
    String messageString;

    public boolean isSuccess(){
        return successString;
    }

    public String getMessage() {
        return messageString;
    }
}

And finally the server side php code is:

<?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);
?>

Where is the problem? What should I do now? Thanks for your time.

like image 608
Hasan Abdullah Avatar asked Dec 02 '16 13:12

Hasan Abdullah


1 Answers

The problem is in your PHP Code. Try this:

<?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);
}
?>
like image 123
Rajesh.k Avatar answered Sep 21 '22 00:09

Rajesh.k