Questa è la prima volta in assoluto che utilizzo JSON System.Net
e il WebRequest
in una delle mie applicazioni. La mia applicazione dovrebbe inviare un payload JSON, simile a quello seguente a un server di autenticazione:
{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}
Per creare questo payload, ho utilizzato la JSON.NET
libreria. Come posso inviare questi dati al server di autenticazione e ricevere la sua risposta JSON? Ecco cosa ho visto in alcuni esempi, ma nessun contenuto JSON:
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseUrl));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = "Parsed JSON Content needs to go here";
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
Tuttavia, questo sembra essere un sacco di codice rispetto all'utilizzo di altri linguaggi che ho usato in passato. Lo sto facendo correttamente? E come posso recuperare la risposta JSON in modo da poterla analizzare?
Grazie, Elite.
Codice aggiornato
// Send the POST Request to the Authentication Server
// Error Here
string json = await Task.Run(() => JsonConvert.SerializeObject(createLoginPayload(usernameTextBox.Text, password)));
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
// Error here
var httpResponse = await httpClient.PostAsync("URL HERE", httpContent);
if (httpResponse.Content != null)
{
// Error Here
var responseContent = await httpResponse.Content.ReadAsStringAsync();
}
}
WebClient.UploadString(JsonConvert.SerializeObjectobj(yourobj))
oHttpClient.PostAsJsonAsync