Search code examples
c#pythonhttphttpwebrequest

Visual C# make web request like python's


i'm having a little piece of python code which makes a web request using the urllib2 as you can se below

import json
import urllib2

urlRequest = urllib2.Request('<link>')
urlRequest.add_header('Content-Type', 'application/json')
urlRequest.add_header('RegistrationToken', '<token>')

data = {
    'content': '<c>',
    'messagetype': 'RichText',
    'contenttype': 'text',
    'id': '<id>'
}

urllib2.urlopen(urlRequest, json.dumps(data))

As i was trying to do it in C# i came across the following problems

  • how to i send the data
  • how do i add the headers?

After googling for a while i managed to write this code:

var request = (HttpWebRequest)WebRequest.Create(url_input.Text);
request.ContentType = "application/json";
request.Headers["RegistrationToken"] = rtoken_input.Text;
request.GetResponse();

I managed to deal with the headers part but the question on the data still remains. Also what is the best way to json encode something?

Anyone who knows what to do?


Solution

  • If you are after serializing the POST data to a JSON payload there are few options.

    1) System.Web.Helpers.Json.Encode MSDN Link

    2) using the JSON.NET library Link

    As for your attempt on converting python to C# you are on the correct track. Refer to this link

    Alternatively you could make use of the WebClient class MSDN Link Refer to this link as well

    Pseudo code

    var client = new WebClient();
    client.Headers.Add("Content-Type", "application/json");
    client.Headers.Add("RegistrationToken", "<token>");
    string response = client.UploadString("<link>", "<json string>");