简体   繁体   English

如何为我的 HttpClient PostAsync 第二个参数设置 HttpContent?

[英]How do I set up HttpContent for my HttpClient PostAsync second parameter?

public static async Task<string> GetData(string url, string data)
{
    UriBuilder fullUri = new UriBuilder(url);

    if (!string.IsNullOrEmpty(data))
        fullUri.Query = data;

    HttpClient client = new HttpClient();

    HttpResponseMessage response = await client.PostAsync(new Uri(url), /*expects HttpContent*/);

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();

    return responseBody;
}

The PostAsync takes another parameter that needs to be HttpContent . PostAsync采用另一个需要为HttpContent参数。

How do I set up an HttpContent ?如何设置HttpContent There Is no documentation anywhere that works for Windows Phone 8.任何地方都没有适用于 Windows Phone 8 的文档。

If I do GetAsync , it works great!如果我做GetAsync ,它工作得很好! but it needs to be POST with the content of key="bla", something="yay"但它需要使用 key="bla", something="yay" 的内容进行 POST

//EDIT //编辑

Thanks so much for the answer... This works well, but still a few unsures here:非常感谢您的回答......这很好用,但这里仍然有一些不确定:

    public static async Task<string> GetData(string url, string data)
    {
        data = "test=something";

        HttpClient client = new HttpClient();
        StringContent queryString = new StringContent(data);

        HttpResponseMessage response = await client.PostAsync(new Uri(url), queryString );

        //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        return responseBody;
    }

The data "test=something" I assumed would pick up on the api side as post data "test", evidently it does not.我认为数据“test=something”会在 api 端作为发布数据“test”获取,显然它不会。 On another matter, I may need to post entire objects/arrays through post data, so I assume json will be best to do so.另一方面,我可能需要通过发布数据发布整个对象/数组,所以我认为 json 最好这样做。 Any thoughts on how I get post data through?关于如何获取发布数据的任何想法?

Perhaps something like:也许是这样的:

class SomeSubData
{
    public string line1 { get; set; }
    public string line2 { get; set; }
}

class PostData
{
    public string test { get; set; }
    public SomeSubData lines { get; set; }
}

PostData data = new PostData { 
    test = "something",
    lines = new SomeSubData {
        line1 = "a line",
        line2 = "a second line"
    }
}
StringContent queryString = new StringContent(data); // But obviously that won't work

This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post .这在Can't find how to use HttpContent以及这篇博文 的一些答案中得到了解答。

In summary, you can't directly set up an instance of HttpContent because it is an abstract class .总之,你不能直接设置HttpContent的实例,因为它是一个抽象类 You need to use one the classes derived from it depending on your need.您需要根据需要使用从它派生的类之一。 Most likely StringContent , which lets you set the string value of the response, the encoding, and the media type in the constructor.最有可能的StringContent ,它允许您在构造函数中设置响应的字符串值、编码和媒体类型。 See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx请参阅: http : //msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

To add to Preston's answer, here's the complete list of the HttpContent derived classes available in the standard library:要添加到 Preston 的答案,以下是标准库中可用的HttpContent派生类的完整列表:

信用:https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

Credit : https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/信用https : //pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

There's also a supposed ObjectContent but I was unable to find it in ASP.NET Core .还有一个假设的ObjectContent但我无法在ASP.NET Core找到它。

Of course, you could skip the whole HttpContent thing all together with Microsoft.AspNet.WebApi.Client extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558 ) and then you can do things like:当然,您可以与Microsoft.AspNet.WebApi.Client扩展一起跳过整个HttpContent内容(您现在必须进行导入才能使其在 ASP.NET Core 中工作: https : //github.com /aspnet/Home/issues/1558 ),然后您可以执行以下操作:

var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
    Title = "New Article Title",
    Body = "New Article Body"
});
    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

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

相关问题 如何设置HttpClient PostAsync来调用新的Web浏览器 - How do I set up HttpClient PostAsync to call a new web browser POST数据后HttpClient.PostAsync HttpContent参数值为null - HttpClient.PostAsync HttpContent parameter value null after POSTing data 如何正确使用 HttpClient PostAsync 参数? - How do I use HttpClient PostAsync parameters properly? 如何在HttpClient / PostAsync中添加标头数据 - How do I add header data in HttpClient/PostAsync 如何使用HttpClient PostAsync计算进度? - How can I calculate progress with HttpClient PostAsync? 使用HttpClient时如何在HttpContent中设置大字符串? - How to set large string inside HttpContent when using HttpClient? 如何正确设置HttpClient的延续? - How do I set up the continuations for HttpClient correctly? 如何验证异步方法和HttpClient.PostAsync调用中的死锁? - How can I verify a deadlock in my async to sync method and HttpClient.PostAsync calls? 如何通过 HttpClient PostAsync 方法将文件和参数上传到远程服务器? - How to upload a file and a parameter to a remote server via HttpClient PostAsync method? 如何将对象传递给 HttpClient.PostAsync 并序列化为 JSON 主体? - How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM