una recorrer por objeto leer example enviar crear consumir consume como cadena archivo c# .net json httpwebrequest json.net

recorrer - ¿Enviar JSON a través de POST en C#y Recibir el JSON devuelto?



leer archivo json c# (2)

Me encontré utilizando la biblioteca HttpClient para consultar las API RESTful, ya que el código es muy sencillo y está completamente asincronizado.

Con dos clases que representan la Estructura JSON que publicó que pueden verse así:

public class Credentials { [JsonProperty("agent")] public Agent Agent { get; set; } [JsonProperty("username")] public string Username { get; set; } [JsonProperty("password")] public string Password { get; set; } [JsonProperty("token")] public string Token { get; set; } } public class Agent { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("version")] public int Version { get; set; } }

podría tener un método como este, que haría su solicitud POST:

var payload = new Credentials { Agent = new Agent { Name = "Agent Name", Version = 1 }, Username = "Username", Password = "User Password", Token = "xxxxx" }; // Serialize our concrete class into a JSON String var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload)); // Wrap our JSON inside a StringContent which then can be used by the HttpClient class var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json"); using (var httpClient = new HttpClient()) { // Do the actual request and await the response var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent); // If the response contains content we want to read it! if (httpResponse.Content != null) { var responseContent = await httpResponse.Content.ReadAsStringAsync(); // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net } }

Esta es la primera vez que uso JSON o incluso System.Net y la parte WebRequest en cualquiera de mis aplicaciones. Se supone que mi aplicación envía una carga útil JSON, similar a la siguiente a un servidor de autenticación:

{ "agent": { "name": "Agent Name", "version": 1 }, "username": "Username", "password": "User Password", "token": "xxxxxx" }

Para crear esta carga útil, utilicé la biblioteca JSON.NET . ¿Cómo enviaría estos datos al servidor de autenticación y recibiría su respuesta JSON? Esto es lo que he visto en algunos ejemplos, pero no en el contenido 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();

Sin embargo, esto parece ser una gran cantidad de código comparado con el uso de otros lenguajes que he usado en el pasado. ¿Estoy haciendo esto correctamente? ¿Y cómo recuperaría la respuesta JSON para poder analizarla?

Gracias, Elite.

Código actualizado

// 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(); } }


Puedes construir tu HttpContent usando la combinación de JObject para evitar y JProperty y luego llamar a ToString() al crear el StringContent :

/*{ "agent": { "name": "Agent Name", "version": 1 }, "username": "Username", "password": "User Password", "token": "xxxxxx" }*/ JObject payLoad = new JObject( new JProperty("agent", new JObject( new JProperty("name", "Agent Name"), new JProperty("version", 1) ), new JProperty("username", "Username"), new JProperty("password", "User Password"), new JProperty("token", "xxxxxx") ) ); using (HttpClient client = new HttpClient()) { var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json"); using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent)) { response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); return JObject.Parse(responseBody); } }