简体   繁体   English

android retrofit 发布请求请求正文为原始 JSON

[英]android retrofit post request request body as raw JSON

This is my first time using the retrofit in android (Java) and i don't know how to do post api这是我第一次在 android (Java) 中使用 retrofit,我不知道如何发布 api

in postman i use Request Body as raw JSON在 postman 我使用请求正文作为原始 JSON

{ "description": "aaaaaa", "reportedpriority_description": "Elevé", "reportedby": "zz", "assetnum": "111", "affectedperson": "ahmed" } {“描述”:“aaaaaa”,“reportedpriority_description”:“Elevé”,“reportedby”:“zz”,“assetnum”:“111”,“受影响的人”:“ahmed”}

someone can help me with example of code?有人可以用代码示例帮助我吗? it return empty response body它返回空响应体

There are two ways you can send a body for Post methods, you can either create a JSON string in the format you want.您可以通过两种方式发送 Post 方法的正文,您可以创建所需格式的 JSON 字符串。 Or you can simply create a model class with the same field names as your JSON keys, and then initialize values to them while sending a request.或者您可以简单地创建一个 model class 与您的 JSON 键具有相同的字段名称,然后在发送请求时为其初始化值。

Model class: Model class:

class Example {

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

Init values:初始值:

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

You can then pass the object to your POST method.然后,您可以将 object 传递给您的 POST 方法。

You can refer to documentations to learn how to code the API methods.您可以参考文档了解如何编写 API 方法。

Hope this works for you!希望这对你有用!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM