dongzhao5970 2015-09-10 15:32
浏览 33
已采纳

使用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.

  • 写回答

2条回答 默认 最新

  • douna2014 2015-09-11 10:45
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化