2013-10-11 136 views
2

您好我是編程新手,所以我的問題可能有點奇怪。我的老闆要求我使用密鑰和消息來創建一個HTTP POST請求來訪問我們的客戶端。如何創建HTTP POST請求

我已經看過文章Handle HTTP request in C# Console application,但它不包括放置密鑰和消息的位置,以便客戶端API知道它。提前感謝幫助。

+0

取決於API如何處理這些價值?作爲標題數據,還是作爲查詢參數?此外,請使用迄今爲止嘗試使用的代碼更新您的問題 – musefan

+0

與您編寫的代碼有關的問題的問題必須描述具體問題 - 並且包含有效的代碼以再現問題本身。請參閱[SSCCE.org](http://sscce.org/)獲取指導。 –

+0

他說他已經準備好端點,可以在那裏測試我是否可以通過HTTP請求在那裏演示站點來訪問那裏的API。 他提到將請求標題中的密鑰連同一條消息一起附上:您好,如果不是,我會收到「歡迎」回覆 「滾出去」。關鍵是長約400個字符。 – veryon

回答

0

你可以使用一個WebClient

using (var client = new WebClient()) 
{ 
    // Append some custom header 
    client.Headers[HttpRequestHeader.Authorization] = "Bearer some_key"; 

    string message = "some message to send"; 
    byte[] data = Encoding.UTF8.GetBytes(message); 

    byte[] result = client.UploadData(data); 
} 

當然取決於API期望如何被髮送的數據和郵件頭。它要求你將不得不去適應這個代碼相匹配的要求。

+0

如何添加您想要發送的URL。 – Zapnologica

2

我相信你想這樣的:

HttpWebRequest httpWReq = 
    (HttpWebRequest)WebRequest.Create("http://domain.com/page.aspx"); 

ASCIIEncoding encoding = new ASCIIEncoding(); 
string postData = "username=user"; 
postData += "&password=pass"; 
byte[] data = encoding.GetBytes(postData); 

httpWReq.Method = "POST"; 
httpWReq.ContentType = "application/x-www-form-urlencoded"; 
httpWReq.ContentLength = data.Length; 

using (Stream stream = httpWReq.GetRequestStream()) 
{ 
    stream.Write(data,0,data.Length); 
} 

HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse(); 

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 
+0

我會立即嘗試並讓您知道結果 – veryon