Search code examples
c#jsonposthttpwebrequest

How to post json into HTTP server


I was wondering how can I make a post from a json to an http server. The code I'm using to do json is as follows:

pedro product = new pedro();
                    product.FirtsName = "Ola";
                    product.ID = 1;
                    product.idade= 10;


                    string json = JsonConvert.SerializeObject(product);

And this is the pedro class:

 public class pedro
    {
        public int ID { get; set; }
        public string FirtsName { get; set; }
        public int idade { get; set; }
    }

Solution

  • With WebApi, you can use something like this:

    string url = "http://url.of.server/";
    Pedro product = new Pedro();
    product.FirtsName = "Ola";
    product.ID = 1;
    product.Idade = 10;
    
    using (var client = new HttpClient())
    {
           client.BaseAddress = new Uri(url);
           client.DefaultRequestHeaders.Accept.Clear();
           client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
           HttpResponseMessage response = client.PostAsJsonAsync(url, product).Result;
           if (response.IsSuccessStatusCode)
           {
                // do something
           }
    }
    

    If you're not using WepApi there are many similar methods, for instance: https://stackoverflow.com/a/39414248/7489072

    Don't Base64 encode the body of your post, as suggested in the comments, unless you absolutely must / want to post binary files AND have control over the receiving webserver. Webservers in 99% of the cases expect a plain text body. If you need to post characters outside the ASCII range, use the correct HTTP headers to specify a Unicode body load.

    Update 1 (headers): The HttpClient class has property DefaultRequestHeaders that can be used to set common request headers, such as AcceptEncoding. If you need a more fine grained control of the content headers, use .PostAsync(string uri, HttpContent content) in stead of .PostAsJsonAsync (that just sets some default headers for Json content)

    using (var client = new HttpClient())
    {
          client.BaseAddress = new Uri(url);
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
          string stringFromObject = JsonConvert.SerializeObject(product);
          HttpContent content = new StringContent(stringFromObject, Encoding.UTF8, "application/json");
          content.Headers.Add("YourCustomHeader", "YourParameter");
    
          HttpResponseMessage response = client.PostAsync(url, content).Result;
          if (response.IsSuccessStatusCode)
          {
              // do something
          }
     }
    

    Update 2 (encoding): To elaborate more on the encoding comments: of course you should escape quotes and the likes. But this is part of the Json standard and should be handled by common encoders / decoders. On top of that, you can use any further encoding for the properties of your serialized object. For instance HTML-encoding on strings and Base64 on binary properties. As long as you know the webserver receiving it will decode it properly.

    { 
      "id": 3,
      "title": "Decode this",
      "description": "this is < HTML encoded >",
      "profileImgBase64": "Nzg5MzQ4IHdleWhmQVMmKihFJiphc3R5WUdkdCphc14qVHlpZg0K"
    }
    

    So encode individual properties, but don't encode the whole Json payload, as you would have to decode it at the beginning of the receiving pipeline and it's just not something webservers will understand.