Ahmed feki
Ahmed feki

Reputation: 31

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

in postman i use Request Body as raw JSON

{ "description": "aaaaaa", "reportedpriority_description": "Elevé", "reportedby": "zz", "assetnum": "111", "affectedperson": "ahmed" }

someone can help me with example of code? it return empty response body

Upvotes: 0

Views: 182

Answers (2)

Nafees
Nafees

Reputation: 1034

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

Upvotes: 1

Yash Joshi
Yash Joshi

Reputation: 627

There are two ways you can send a body for Post methods, you can either create a JSON string in the format you want. 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:

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.

You can refer to documentations to learn how to code the API methods.

Hope this works for you!

Upvotes: 0

Related Questions