Dr. Ehsan Ali
Dr. Ehsan Ali

Reputation: 4884

How to send http POST parameters in Android using Retrofit and receive it via PHP?

The API class is:

public interface api {
  @Headers("Content Type: application/json")
  @FormUrlEncoded
  @POST("/api/login.php")
  public void login(@Field("username") String uname,
                  @Field("password") String pass,
                  Callback<macaronmodel> response);
}

The model class looks like this:

public class mymodel {
  @SerializedName("success")
  private String success;
  @SerializedName("user_id")
  private String user_id;
  @SerializedName("error_code")
  private String error_code;
}

The rest adapter is used in my Android app client like this:

  RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("http://myip")
    .setLogLevel(RestAdapter.LogLevel.FULL)
    .build();
    macaronapi api = restAdapter.create(api.class);
    api.login(mUsername, mPassword, new Callback<mymodel>() {
    @Override
    public void success(mymodel my_model, Response response) {
      Log.d("Test", "success");
    }

    @Override
    public void failure(RetrofitError retrofitError) {
      Log.d("Test", "failure");
      retrofitError.printStackTrace();
    }
  });

Everything works fine except, success function is also called, but in server side my PHP code can not access the POST parameters by using $_POST['username'], or $_POST['password'] so it returns a JSON error message.

It seems I still can not figure out the proper way to send POST parameters to a REST server and access them by using PHP.

Upvotes: 0

Views: 1586

Answers (1)

Dr. Ehsan Ali
Dr. Ehsan Ali

Reputation: 4884

Ok I got it fixed.

I only had to remove the header line from api interface:

 public interface api {
   @FormUrlEncoded
   @POST("/api/login.php")
   public void login(@Field("username") String uname,
              @Field("password") String pass,
              Callback<macaronmodel> response);
 }

Upvotes: 1

Related Questions