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;
}
The PostAsync
takes another parameter that needs to be HttpContent
.
How do I set up an HttpContent
? There Is no documentation anywhere that works for Windows Phone 8.
If I do GetAsync
, it works great! but it needs to be POST with the content of key="bla", something="yay"
//EDIT
Thanks so much for the answer... This works well, but still a few unsures here:
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;
}
The data "test=something" I assumed would pick up on the api side as post data "test", evidently it does not. On another matter, I may need to post entire objects/arrays through post data, so I assume json will be best to do so. Any thoughts on how I get post data through?
Perhaps something like:
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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…