简体   繁体   中英

Rest API Post Json using C# with two parameters

I need to do a Post request on a REST api, the api accepts JSON data type. I have two parameters to include, startdate and enddate . Any guide in C#? Im getting error (415) Unsupported Media Type. I believe its because my post request doesnt have a proper json body

        var request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "POST";
        request.Headers.Add(HttpRequestHeader.Authorization, "Bearer xxx");  
        request.ContentType = "application/json; charset=utf-8";

        // Get response here
        var response = request.GetResponse() as HttpWebResponse;
      
        if (response.StatusCode == HttpStatusCode.OK)
        {
            Console.WriteLine(response.ToString());
            Console.ReadKey();
            // ....
        }

This is how I do it with an example of how to set a header.

using Newtonsoft.Json;

// e.g. update a user's email address via REST POST
dynamic user = new JObject();
user.Email = "testuser@test.com";
var json = user.ToString();

// json is then
// {"Email":"testuser@test.com"}
// and the json is POSTed to the appropriate REST url

var client = new HttpClient
{
    Timeout = TimeSpan.FromSeconds(10)
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "user agent name");

var request = GetRequestMessage(uri, accessToken, json);
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();

private HttpRequestMessage GetRequestMessage(string uri, string accessToken, string jsonPayload)
{
    var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uri)
    {
        Headers = { { "Authorization", $"Bearer {accessToken}" } }
    };

    httpRequestMessage.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

    return httpRequestMessage;
}

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