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

时间:2017-09-04 21:26:23

标签: c# api asp.net-web-api

我需要在C#中进行一些api调用。我正在使用Microsoft的Web API Client来做到这一点。我成功发出了一些POST请求,但我不知道如何将“Body”字段添加到我的请求中。任何的想法 ? 这是我的代码:

#   Edit FITS headers to recenter images at galactic center
w1_resampled_header = w1header
w2_resampled_header = w2header

w1_resampled_header['CRPIX1'] = w1header['CRPIX1']
w1_resampled_header['CRPIX2'] = w1header['CRPIX2']
w2_resampled_header['CRPIX1'] = w2header['CRPIX1']
w2_resampled_header['CRPIX2'] = w2header['CRPIX2']                                                

#   Save as FITS files and close
fits.writeto('w1_resampled.fits',
             w1_resampled,
             w1_resampled_header,
             overwrite = True)
fits.writeto('w2_resampled.fits',
             w2_resampled,
             w2_resampled_header,
             overwrite = True)

3 个答案:

答案 0 :(得分:4)

步骤1.选择派生自HttpContent的类型。如果您想使用运行时代码编写大量内容,可以使用StreamContent并在其上打开某种StreamWriter。对于简短的事情,请使用StringContent。您还可以为自定义内容派生自己的类。

步骤2.将内容传递给HttpClient.PostAsync

这是一个使用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);

另见How do I set up HttpContent?

答案 1 :(得分:2)

感谢thisthis,我终于找到了使用标题和正文内容发送帖子请求的解决方案。这是代码:

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

答案 2 :(得分:1)

更容易理解

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