0

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; }
    }
Pedro Azevedo
  • 218
  • 4
  • 11
  • You can use [RestSharp](http://restsharp.org/) – Aleks Andreev Aug 24 '17 at 08:42
  • 1
    Possible duplicate of [How to post JSON to the server?](https://stackoverflow.com/questions/9145667/how-to-post-json-to-the-server) – Aleks Andreev Aug 24 '17 at 08:43
  • Convert the JSON to a string then base64 the string, you then need to base64 decode the data on the server and convert back to an object....its sounds more complicated than it is and only requires two function calls at each end. – SPlatten Aug 24 '17 at 08:45
  • 1
    @SPlatten why I need to base64 my string ? – Pedro Azevedo Aug 24 '17 at 08:46
  • @PedroAzevedo, because the data you are posting may contain characters that will break the protocol when transmitting to the server. HTTP Protocol is just a string of data, therefore you need to manage the data. – SPlatten Aug 24 '17 at 08:47
  • @SPlatten But how can I convert to base64? – Pedro Azevedo Aug 24 '17 at 08:49
  • If you are coding in C#, this might help: https://stackoverflow.com/questions/11743160/how-do-i-encode-and-decode-a-base64-string – SPlatten Aug 24 '17 at 08:50

1 Answers1

0

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.

Karim Ayachi
  • 162
  • 7
  • HttpClient.DefaultRequestHeaders has many pre-defined properties for the most common request-headers. E.g. HttpClient.DefaultRequestHeaders.AcceptEncoding If you need to set more than only request headers, use .PostAsync(string uri, HttpContent content) and set the content headers of content. – Karim Ayachi Aug 24 '17 at 09:51
  • Can you update your answer with one header exemple ? – Pedro Azevedo Aug 24 '17 at 10:01
  • Updated the answer – Karim Ayachi Aug 24 '17 at 10:20