简体   繁体   中英

How do I format and post Json in the post request body (RestSharp)

I don't understand how to sent this json in the request body. Here is the json from the postman create collection body ( https://www.postman.com/postman/workspace/postman-public-workspace/request/12959542-049042b8-447f-4f71-8b79-ae978cf40a04 ):

{
    "collection": {
        "info": {
            "name": "Sample Collection 909",
            "description": "This is just a sample collection.",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
        },
        "item": [
            {
                "name": "This is a folder",
                "item": [
                    {
                        "name": "Sample POST Request",
                        "request": {
                            "url": "https://postman-echo.com/post",
                            "method": "POST",
                            "header": [
                                {
                                    "key": "Content-Type",
                                    "value": "application/json"
                                }
                            ],
                            "body": {
                                "mode": "raw",
                                "raw": "{\"data\": \"123\"}"
                            },
                            "description": "This is a sample POST Request"
                        }
                    }
                ]
            },
            {
                "name": "Sample GET Request",
                "request": {
                    "url": "https://postman-echo/get",
                    "method": "GET",
                    "description": "This is a sample GET Request"
                }
            }
        ]
    }
}

Json above works fine using the Postman app, my attempt at it:

RestSharp.Settings.Init("collections", Method.Post);
RestSharp.Settings.AddHeader("X-Api-Key", "I hid my key");
RestSharp.Settings.restRequest.RequestFormat = DataFormat.Json;

RestSharp.Settings.restRequest.AddParameter("application/json; charset=utf-8", "{\n    \"collection\": {\n        \"info\": {\n            \"name\": \"Sample Collection 909\",\n            \"description\": \"This is just a sample collection.\",\n            \"schema\": \"https://schema.getpostman.com/json/collection/v2.1.0/collection.json\"\n        },\n        \"item\": [\n            {\n                \"name\": \"This is a folder\",\n                \"item\": [\n                    {\n                        \"name\": \"Sample POST Request\",\n                        \"request\": {\n                            \"url\": \"https://postman-echo.com/post\",\n                            \"method\": \"POST\",\n                            \"header\": [\n                                {\n                                    \"key\": \"Content-Type\",\n                                    \"value\": \"application/json\"\n                                }\n                            ],\n                            \"body\": {\n                                \"mode\": \"raw\",\n                                \"raw\": \"{\\\"data\\\": \\\"123\\\"}\"\n                            },\n                            \"description\": \"This is a sample POST Request\"\n                        }\n                    }\n                ]\n            },\n            {\n                \"name\": \"Sample GET Request\",\n                \"request\": {\n                    \"url\": \"https://postman-echo/get\",\n                    \"method\": \"GET\",\n                    \"description\": \"This is a sample GET Request\"\n                }\n            }\n        ]\n    }\n}",ParameterType.RequestBody);

var response = RestSharp.Settings.restClient.ExecuteAsync(RestSharp.Settings.restRequest).Result;

Console.WriteLine("Returned http status code is: " + response.StatusCode + " expected OK");

Assert.IsTrue((int)response.StatusCode == 200);

Have a look at the RestSharp quick start guide . There are a couple of methods that could come in useful for you.

If you have an object to serialize you can use AddJsonBody() to post Json. This is taken from that guide:

For example, you'd only need these lines to make a request with JSON body:

 var request = new RestRequest("address/update").AddJsonBody(updatedAddress); var response = await client.PostAsync<AddressUpdateResponse>(request);

AddJsonBody automatically sets the ContentType and DataFormat :

There is no need to set the Content-Type or add the DataFormat parameter to the request when using those methods, RestSharp will do it for you.


However, since you already have Json as a string, the correct method to use is AddStringBody() (credit to Alexey Zimarev for the comment). You need to pass the content type:

If you have a pre-serialized payload like a JSON string, you can use AddStringBody to add it as a body parameter. You need to specify the content type, so the remote endpoint knows what to do with the request body. For example:

 ``` const json = // your json string; request.AddStringBody(json, ContentType.Json); ```

I'd recommend awaiting the response too, as in the examples above, rather than using .Result .

try this

var client = new RestClient("http://..");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", json,  ParameterType.RequestBody);
IRestResponse response =  await client.ExecuteAsync(request);
var jsonOutput=response.Content;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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