gpt4 book ai didi

c# - 如何使用 WebRequest 发布一些数据并读取响应?

转载 作者:IT王子 更新时间:2023-10-29 04:40:54 26 4
gpt4 key购买 nike

需要让服务器对 API 进行 POST,如何将 POST 值添加到 WebRequest 对象以及如何发送它并获得响应(它将是一个字符串)?

我需要 POST 两个值,有时更多,我在这些示例中看到它说 string postData = "a string to post";但是我如何让我正在发布的东西知道有多个表单值?

最佳答案

来自 MSDN

// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();

考虑到信息必须以key1=value1&key2=value2的格式发送

关于c# - 如何使用 WebRequest 发布一些数据并读取响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2860636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com