Inviare JSON tramite POST in C # e ricevere il JSON restituito?


86

Questa è la prima volta in assoluto che utilizzo JSON System.Nete il WebRequestin 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.NETlibreria. 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();
    }
}

2
Puoi provare WebClient.UploadString(JsonConvert.SerializeObjectobj(yourobj))oHttpClient.PostAsJsonAsync
LB

Risposte:


136

Mi sono ritrovato a utilizzare la libreria HttpClient per interrogare le API RESTful poiché il codice è molto semplice e completamente asincrono.

(Modifica: aggiunta di JSON dalla domanda per chiarezza)

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

Con due classi che rappresentano la struttura JSON che hai pubblicato che potrebbe assomigliare a questo:

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; }
}

potresti avere un metodo come questo, che farebbe la tua richiesta 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
    }
}

5
perfetto, ma qual è l'attesa Task.run (()?
Hunter Mitchell

24
Non dovresti usare Task.Run su metodi associati alla CPU sincrona poiché stai semplicemente sparando un nuovo thread senza alcun vantaggio!
Stephen Foster

2
Non è necessario digitare JsonPropertyper ogni proprietà. Basta usare Json.Net costruito in CamelCasePropertyNamesContractResolver o un customNamingStrategy per personalizzare il processo di serializzazione
Seafish

6
Nota a margine: non utilizzare a usingcon HttpClient. Vedi: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong
maxshuty

4
Con System.Net.Http.Formatting hai definito i metodi di estensione: "await httpClient.PostAsJsonAsync (" api / v1 / domain ", csObjRequest)"
hB0

15

Usando il pacchetto NuGet JSON.NET e i tipi anonimi, puoi semplificare ciò che suggeriscono gli altri poster:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

6

Puoi costruire il tuo HttpContentusando la combinazione di JObjectper evitare JPropertye quindi chiamarlo ToString()quando costruisci 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);
            }
        }

Come eviti gli Exception while executing function. Newtonsoft.Json: Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArrayerrori?
Jari Turkia

1
Non si suppone che un'istanza HttpClient crei utilizzando il costrutto. L'istanza deve essere creata una volta e utilizzata in tutta l'applicazione. Questo perché utilizza il proprio pool di connessioni. Il tuo codice tende principalmente a generare SocketException. docs.microsoft.com/en-us/dotnet/api/…
Harun Diluka Heshan

2

Puoi anche utilizzare il metodo PostAsJsonAsync () disponibile in HttpClient ()

   var requestObj= JsonConvert.SerializeObject(obj);
   HttpResponseMessage response = await    client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);


1
Puoi aggiungere una spiegazione su cosa fa il tuo codice e come risolve il problema?
Nilambar Sharma

Puoi prendere qualsiasi oggetto che desideri postare e serializzarlo usando SerializeObject (); var obj= new Credentials { Agent = new Agent { Name = "Agent Name", Version = 1 }, Username = "Username", Password = "User Password", Token = "xxxxx" }; Quindi, senza doverlo convertire in httpContent, puoi utilizzare PostAsJsonAsync () passando l'URL dell'endpoint e l'oggetto JSON convertito stesso.
Rukshala Weerasinghe
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.