如何在.net中将Curl命令转换为HttpWebRequest?

时间:2016-07-20 10:05:21

标签: c# .net rest curl httpwebrequest

您好我正在尝试使用vs2010 .net来使用第三方Rest服务,这是cURL命令从该服务获取一些数据的示例:

curl -k --header "X-Authorization: authorizationString" -G -X GET -d 'message' https://WebsiteAddress.com/api/command/914
  1. 如何设置参数-G -X -GET?
  2. 如何将-H header参数更改为--header?或者我必须这样做吗?
  3. 这是我到目前为止所做的:

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

1 个答案:

答案 0 :(得分:0)

它应该是这样的:

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

阅读本文:curl.haxx.se/docs/manpage.html
您正在尝试建立连接HTTP GET INSECURE WITH EXTRA HEADER,'message'将连接到您的URL。