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
,效果很好!但它需要与 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