简体   繁体   中英

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

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? .

Thanks to this and this , I finally found the solution to send post requests with headers AND body content. Here's the code:

        var cl = new HttpClient();
        cl.BaseAddress = new Uri("< YOUR URL >");
        int _TimeoutSec = 90;
        cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
        string _ContentType = "application/x-www-form-urlencoded";
        cl.DefaultRequestHeaders.Add(key, value);
        cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
        cl.DefaultRequestHeaders.Add("key", "value");
        cl.DefaultRequestHeaders.Add("key", "value");
        var _UserAgent = "d-fens HttpClient";
        cl.DefaultRequestHeaders.Add("User-Agent", _UserAgent);

        var nvc = new List<KeyValuePair<string, string>>();
        nvc.Add(new KeyValuePair<string, string>("key of content", "value"));
        var req = new HttpRequestMessage(HttpMethod.Post, "http://www.t-lab.fr:3000/add_tips") { Content = new FormUrlEncodedContent(nvc) };
        var res = cl.SendAsync(req);

a little more understandable

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
    client.DefaultRequestHeaders.Add("Accept", "*/*");

    var Parameters = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("Id", "1"),
    };

    var Request = new HttpRequestMessage(HttpMethod.Post, "Post_Url")
    {
        Content = new FormUrlEncodedContent(Parameters)
    };

    var Result = client.SendAsync(Request).Result.Content.ReadAsStringAsync();
}

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