Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Body content in POST request

I need to make some api calls in C#. I'm using Web API Client from Microsoft to do that. I success to make some POST requests, but I don't know how to add the field "Body" into my requests. Any idea ? Here's my code:

    static HttpClient client = new HttpClient();
    public override void AwakeFromNib()
    {
        base.AwakeFromNib();
        notif_button.Activated += (sender, e) => {
        };
        tips_button.Activated += (sender, e) =>
        {
            Tip t1 = new Tip(title_tips.StringValue, pic_tips.StringValue, content_tips.StringValue, "TEST");
            client.BaseAddress = new Uri("my_url");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            CreateProductAsync(t1).Wait();
        };
    }

    static async Task<Uri> CreateProductAsync(Tip tips)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync("api/add_tips", tips);
        response.EnsureSuccessStatusCode();
        return response.Headers.Location;
    }
like image 202
Baptiste Avatar asked Sep 04 '17 21:09

Baptiste


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


1 Answers

Step 1. Choose a type that derives from HttpContent. If you want to write a lot of content with runtime code, you could use a StreamContent and open some sort of StreamWriter on it. For something short, use StringContent. You can also derive your own class for custom content.

Step 2. Pass the content in a call to HttpClient.PostAsync.

Here's an example that uses StringContent to pass some JSON:

string json = JsonConvert.SerializeObject(someObject);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync("http://www.foo.bar", httpContent);

See also How do I set up HttpContent?.

like image 158
John Wu Avatar answered Sep 22 '22 22:09

John Wu