2014-04-17 17 views
0

我正在處理的當前項目需要從機器人到我的網站的雙向通信。如何處理C#.NET POST和GET命令

假設示例URL是www.example.com/foobar.php什麼的,你能解釋我如何POST和GET數據?

非常感謝。

P.S. - 使用webclient的權利?

+0

可能重複http://stackoverflow.com/questions/4015324/http-request-with-post – mnme

回答

1

是的,你可以使用WebClient

using (WebClient client = new WebClient()) 
{ 
    NameValueCollection nvc = new NameValueCollection() 
    { 
     { "foo", "bar"} 
    }; 

    byte[] responseBytes = client.UploadValues("http://www.example.com/foobar.php", nvc); 
    string response = System.Text.Encoding.ASCII.GetString(responseBytes); 
} 
+0

所以'nvc'包含在URL中尋找參數?以及如何解析響應?抱歉。新東西 – user2794212

+0

'NameValueCollection'是你想發佈的參數。我的例子展示瞭如何獲得迴應。 – DGibbs

+0

這樣的響應字符串,它包含數據的格式是什麼?給出foo = 1和bar = 2 ..字符串是簡單的'12'嗎? – user2794212

0

您可以使用Web客戶端

查找方法UploadString和DownloadString

2

我建議使用RestSharp。這比使用Web客戶端輕鬆了許多,併爲您提供了更多的選擇:

var client = new RestClient("http://www.example.com/"); 

//to POST data: 
var postRequest = new RestRequest("foo.php", Method.POST); 
postRequest.AddParameter("name", "value"); 
var postResponse = client.Execute(postRequest); 

//postResponse.Content will contain the raw response from the server 


//To GET data 
var getRequest = new RestRequest("foo.php", Method.GET); 
getRequest.AddParameter("name", "value"); 
var getResponse = client.Execute(getRequest);