Search code examples
c#.netrestcurlhttpwebrequest

How to convert Curl command to HttpWebRequest in .net?


Hello I am trying to consume a 3rd party Rest service using vs2010 .net and this is example of cURL command to get some data from this service:

curl -k --header "X-Authorization: authorizationString" -G -X GET -d 'message' https://WebsiteAddress.com/api/command/914
  1. How to set parameters -G -X -GET?
  2. How to change -H header parameter to --header? Or do I have to do that?

This is what I have so far:

string authorizationString = "bla bla";
string message = "my Message";
string url = "https://WebsiteAddress.com/api/command/914";
var req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "application/json";
req.Method = "Get";
req.Headers.Add("X-Authorization", authorizationString);

//bypassing untrusted certificate 
//if DUBUG
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
//end DEBUG

using (var PostData = new StreamWriter(req.GetRequestStream()))
{
    PostData.Write(message);
    PostData.Flush();
}

var response = (HttpWebResponse)req.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
    //TO DO:
}

Solution

  • It should be something like this:

    using(WebClient webClient = new WebClient())
    {
        webClient.Headers.Add("X-Authorization", "authorizationString");
        string response = webClient.DownloadString("https://WebsiteAddress.com/api/command/914?message");
    }
    

    Read this : curl.haxx.se/docs/manpage.html
    You are trying to make a connection HTTP GET INSECURE WITH EXTRA HEADER and 'message' will be concatenate to your url.