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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器