简体   繁体   English

C# - POST 请求中的正文内容

[英]C# - Body content in POST request

I need to make some api calls in C#.我需要在 C# 中进行一些 api 调用。 I'm using Web API Client from Microsoft to do that.我正在使用 Microsoft 的 Web API 客户端来做到这一点。 I success to make some POST requests, but I don't know how to add the field "Body" into my requests.我成功提出了一些 POST 请求,但我不知道如何将字段“Body”添加到我的请求中。 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 .步骤 1. 选择派生自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.如果您想使用运行时代码编写大量内容,您可以使用StreamContent并在其上打开某种 StreamWriter。 For something short, use StringContent .简而言之,请使用StringContent You can also derive your own class for custom content.您还可以为自定义内容派生自己的类。

Step 2. Pass the content in a call to HttpClient.PostAsync .步骤 2. 在对HttpClient.PostAsync的调用中传递内容。

Here's an example that uses StringContent to pass some JSON:这是一个使用 StringContent 传递一些 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?另请参阅如何设置 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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