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
最佳答案
在Can't find how to use HttpContent以及此blog post的某些答案中都可以得到回答。
总而言之,您不能直接设置HttpContent
的实例,因为它是一个抽象类。您需要根据需要使用从其派生的类之一。最有可能的StringContent
,它使您可以在构造函数中设置响应的字符串值,编码和媒体类型。另请:http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx
关于c# - 如何为HttpClient PostAsync第二个参数设置HttpContent?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18971510/