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”获得,显然不是。另一方面,我可能需要通过发布数据来发布整个对象/数组,因此我认为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