【问题标题】:android retrofit post request request body as raw JSONandroid 改造发布请求正文为原始 JSON
【发布时间】:2021-05-25 05:30:15
【问题描述】:

这是我第一次在android(Java)中使用改造,我不知道如何做post api

在邮递员中,我使用请求正文作为原始 JSON

{ “描述”:“aaaaaa”, "reportedpriority_description": "Elevé", “报告人”:“zz”, “资产”:“111”, “受影响的人”:“艾哈迈德” }

有人可以帮助我提供代码示例吗?它返回空响应体

【问题讨论】:

    标签: android retrofit


    【解决方案1】:
      void requestcall(){
             try
                {
                   
                    HashMap respMap = new HashMap<>();
                    respMap.put("Key1", "Value1");
                    respMap.put("Key2", "Value2");
                    respMap.put("Key3", "Value3");
                    String resultString = convertToJson(respMap);
                    sendToServer(resultString);
                }
                catch (Exception e)
                { }
        }
        
           public static String convertToJson(HashMap<String, String> respMap)
            {
                JSONObject respJson = new JSONObject();
                JSONObject respDetsJson = new JSONObject();
                Iterator mapIt = respMap.entrySet().iterator();
        
                try
                {
                    while (mapIt.hasNext()) {
                        HashMap.Entry<String, String> entry = (HashMap.Entry) mapIt.next();
                        respDetsJson.put(entry.getKey(), entry.getValue());
                    }
                    //change according to your response
                    respJson.put("RESPONSE", respDetsJson);
                }
                catch (JSONException e)
                {
                    return  "";
                }
        
                return respJson.toString();
            }
    

    【讨论】:

    • 我将如何使用这个方法requestcall?我在哪里插入baseurl?
    • 你不是在使用改造网络吗??
    • 是的,请告诉我如何应用这些方法.. 在@Body 作为地图输入的界面中??
    【解决方案2】:

    您可以通过两种方式发送 Post 方法的正文,您可以创建所需格式的 JSON 字符串。或者,您可以简单地创建一个与 JSON 键具有相同字段名称的模型类,然后在发送请求时为其初始化值。

    模型类:

    class Example {
    
    var description: String? = null
    var reportedpriority_description: String? = null
    var reportedby: String? = null
    var assetnum: String? = null
    var affectedperson: String? = null
    }
    

    初始值:

    val obj = Example()
    obj.description = "aaaaaa"
    // and so on
    

    然后您可以将对象传递给您的 POST 方法。

    您可以参考documentations 了解如何编写 API 方法。

    希望这对你有用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-19
      • 2020-06-18
      • 1970-01-01
      • 2019-12-11
      • 2017-06-17
      • 2021-03-04
      • 2018-08-08
      相关资源
      最近更新 更多