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端作为post数据“test”,显然它不是。在另一个问题上,我可能需要通过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