2016-07-20 46 views
0

你好我試圖用VS2010 .NET消耗第三方REST服務,這是例如捲曲的命令,從該服務中獲得的一些數據:如何將Curl命令轉換爲.net中的HttpWebRequest?

curl -k --header "X-Authorization: authorizationString" -G -X GET -d 'message' https://WebsiteAddress.com/api/command/914 
  1. 如何設置參數-G-X - 得到?
  2. 如何將-H頭參數更改爲--header?或者我必須這樣做?

這是我到目前爲止有:

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

它看起來像消息應該在URL字符串,所以我有改變這一點:string message =「my Message」; string url =「https://WebsiteAddress.com/api/command/914」;爲此:string message =「my Message」; string url =「https://WebsiteAddress.com/api/command/914」+ message;然後使用(var PostData = new StreamWriter(req.GetRequestStream()))刪除 Postgre.Write(message); PostData.Flush(); }這個,它開始工作; – Czarkek

回答

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'將連接到您的網址。

+0

如果我們將content.type標記爲「application/json」,我們是否需要使用JSON發送數據?如果是的話,我們如何將字符串轉換爲C#或.NET中的JSON對象? – kvk30