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;
}
我原以为数据 "test=something" 会被 API 端视为 "test" 的 post 数据,但显然并非如此。另外,我可能需要将整个对象/数组通过 post 数据进行发布,因此我认为使用 json 是最好的方式。您有什么想法如何将 post 数据发送出去吗?
或许可以尝试类似这样的方法:
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