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;
}
La PostAsyncprende un altro parametro che deve essere HttpContent.
Come si configura un HttpContent? Non esiste alcuna documentazione che funzioni per Windows Phone 8.
Se lo faccio GetAsync, funziona benissimo! ma deve essere POST con il contenuto di key = "bla", qualcosa = "yay"
//MODIFICARE
Grazie mille per la risposta ... Funziona bene, ma qui ci sono ancora alcuni dubbi:
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;
}
I dati "test = qualcosa" supponevo che sarebbero stati raccolti dal lato API come post test "test", evidentemente no. Su un altro argomento, potrei aver bisogno di pubblicare interi oggetti / array attraverso i dati di post, quindi presumo che Json sia il migliore per farlo. Qualche idea su come ottengo i dati dei post?
Forse qualcosa del tipo:
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
