您好我是编程新手,所以我的问题可能有点奇怪。我的老板要求我使用密钥和消息来创建一个HTTP POST请求来访问我们的客户端。如何创建HTTP POST请求
我已经看过文章Handle HTTP request in C# Console application,但它不包括放置密钥和消息的位置,以便客户端API知道它。提前感谢帮助。
您好我是编程新手,所以我的问题可能有点奇怪。我的老板要求我使用密钥和消息来创建一个HTTP POST请求来访问我们的客户端。如何创建HTTP POST请求
我已经看过文章Handle HTTP request in C# Console application,但它不包括放置密钥和消息的位置,以便客户端API知道它。提前感谢帮助。
你可以使用一个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期望如何被发送的数据和邮件头。它要求你将不得不去适应这个代码相匹配的要求。
如何添加您想要发送的URL。 – Zapnologica
我相信你想这样的:
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();
我会立即尝试并让您知道结果 – veryon
取决于API如何处理这些价值?作为标题数据,还是作为查询参数?此外,请使用迄今为止尝试使用的代码更新您的问题 – musefan
与您编写的代码有关的问题的问题必须描述具体问题 - 并且包含有效的代码以再现问题本身。请参阅[SSCCE.org](http://sscce.org/)获取指导。 –
他说他已经准备好端点,可以在那里测试我是否可以通过HTTP请求在那里演示站点来访问那里的API。 他提到将请求标题中的密钥连同一条消息一起附上:您好,如果不是,我会收到“欢迎”回复 “滚出去”。关键是长约400个字符。 – veryon