最佳答案
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;
}
PostAsync
接受另一个需要为 HttpContent
的参数。
我如何设置一个 HttpContent
? 没有任何地方的文档,为 Windows Phone 8工作。
如果我使用 GetAsync
,它工作得很好! 但是它需要是 POST,其内容为 key = “ bla”,something = “ yay”
//编辑
非常感谢您的回答... ... 这个方法很有效,但仍有一些不确定性:
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;
}
我假设在 api 方面,数据“ test = something”将作为后期数据“ test”获取,但显然它并非如此。另一方面,我可能需要通过 post 数据发布整个对象/数组,因此我假设 json 将是最佳选择。关于如何获取邮件数据有什么想法吗?
比如:
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