使用Retrofit将POJO发布到PHP应用程序

问题描述:

I am trying to send a POJO via a POST request through Retrofit to a PHP application and I wish to have the fields received via PHP's $_POST variable. This seems easy but I can't seem to get it to work.

My retrofit interface:

public interface APIMethods {

    @FormUrlEncoded
    @POST("/api/api/postUser/")
    void postUser(
            @Query("auth_token") String auth_token,
            @Body User user,
            Callback<RESTResponse> callback
    );
}

The request went through without errors but $_POST is empty.

我试图通过POST请求通过Retrofit发送POJO到PHP应用程序,我希望有这些字段 通过PHP的$ _POST变量接收。 这似乎很容易,但我似乎无法让它工作。 p>

我的改造界面: p>

  public interface APIMethods {
  
 @FormUrlEncoded 
 @POST(“/ api / api / postUser /”)
 void postUser(
 @Query(“auth_token”)字符串auth_token,
 @Body用户用户,
回调&lt; RESTResponse&gt;回调 
); 
} 
  code>  pre> 
 
 

请求没有错误但$ _POST为空。 p> div>

Figured it out, based on Victory's suggestion of FieldMap.

Interface:

public interface APIMethods {

    @FormUrlEncoded
    @POST("/api/api/postUser/")
    void postUser(
            @Header("auth_token") String auth_token,
            @FieldMap Map<String, String> userFields,
            Callback<RESTResponse> callback
    );
}

To convert a User POJO to Map<String, String> FieldMap, I used Jackson's ObjectMapper:

// Get a REST adapter
RestAdapter restAdapter = RestAdapterFactory.getInstance();
// Create API instance
IAPIMethods methods = restAdapter.create(IAPIMethods.class);

    // Define callback
    Callback<RESTResponse> callback = new Callback<RESTResponse>() {
        @Override
        public void success(RESTResponse restResponse, Response response) {
            String res = restResponse.responseText;
            if(restResponse.status != 1){
                Toast.makeText(getBaseContext(), "Error: " + res, Toast.LENGTH_LONG).show();
            }else{
                textView.setText(res);
            }

            Log.d("Debug", res);

        }

        @Override
        public void failure(RetrofitError error) {
            Log.e("RetrofitError", error.toString());
        }
    };

// Instantiate User object/bean
User user = new User();
// Set user properties
user.username = "...";
...

// Instantiate Jackson's ObjectMapper to convert User POJO to Map<String, String>
ObjectMapper mapper = new ObjectMapper();
Map<String, String> userFields = mapper.convertValue(user, Map.class);
methods.postUser(API_KEY, userFields, callback);

In PHP, access user data with $_POST and Headers with getallheaders();

You need to use the @Field annotation to set the key value pair for @FormUrlEncode to send.

 @FormUrlEncoded
 @POST("/")
 void example(@Field("foo") String name, @Field("bar") String occupation);
 }

official docs

There is also the very handy FieldMap