How do I set up HttpContent for my HttpClient PostAsync second parameter?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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; } |
如何设置
如果我执行
//编辑
非常感谢您的回答...效果很好,但是在这里仍然不确定:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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; } |
我假设数据" test = something"将在api方面作为发布数据" test"获得,显然不是。 另一方面,我可能需要通过发布数据来发布整个对象/数组,因此我认为json将是最好的选择。 关于如何获取帖子数据的任何想法?
也许像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 |
在有关Cant查找如何使用HttpContent的一些答案以及本博客文章中,都对此进行了回答。
总而言之,您不能直接设置
为了增加Preston的答案,以下是标准库中提供的
信用:https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/
还有一个假定的
当然,您可以跳过整个
1 2 3 4 5 | var response = await client.PostAsJsonAsync("AddNewArticle", new Article { Title ="New Article Title", Body ="New Article Body" }); |