【问题标题】:How to use WebRequest to POST some data and read response?如何使用 WebRequest 发布一些数据并读取响应?
【发布时间】:2011-02-21 02:00:51
【问题描述】:

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

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

【问题讨论】:

标签: c# asp.net webrequest


【解决方案1】:

来自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的格式发送

【讨论】:

  • 谢谢,所以它就像一个查询字符串,正是我需要的,你赢了
  • 是的,基本上,所以要小心特殊字符。您需要对键和值进行编码
【解决方案2】:

这对我有用。我确信它可以改进,因此请随时提出建议或进行编辑以使其变得更好。

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
try
{       
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
    {
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
            sw.Write(jsonData);
    }

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
        {
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
        }
    }
}
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

【讨论】:

    【解决方案3】:

    这是一个使用 HttpWebRequest 和 HttpWebResponse 对象发布到 Web 服务的示例。

    StringBuilder sb = new StringBuilder();
        string query = "?q=" + latitude + "%2C" + longitude + "&format=xml&key=xxxxxxxxxxxxxxxxxxxxxxxx";
        string weatherservice = "http://api.worldweatheronline.com/free/v1/marine.ashx" + query;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherservice);
        request.Referer = "http://www.yourdomain.com";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        Char[] readBuffer = new Char[256];
        int count = reader.Read(readBuffer, 0, 256);
    
        while (count > 0)
        {
            String output = new String(readBuffer, 0, count);
            sb.Append(output);
            count = reader.Read(readBuffer, 0, 256);
        }
        string xml = sb.ToString();
    

    【讨论】:

      【解决方案4】:

      可以在此处找到更强大、更灵活的示例:C# File Upload with form fields, cookies and headers

      【讨论】:

        【解决方案5】:

        下面是从文本文件中读取数据并将其发送到处理程序进行处理并从处理程序接收响应数据并将其读取并将数据存储在字符串构建器类中的代码

         //Get the data from text file that needs to be sent.
                        FileStream fileStream = new FileStream(@"G:\Papertest.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                        byte[] buffer = new byte[fileStream.Length];
                        int count = fileStream.Read(buffer, 0, buffer.Length);
        
                        //This is a handler would recieve the data and process it and sends back response.
                        WebRequest myWebRequest = WebRequest.Create(@"http://localhost/Provider/ProcessorHandler.ashx");
        
                        myWebRequest.ContentLength = buffer.Length;
                        myWebRequest.ContentType = "application/octet-stream";
                        myWebRequest.Method = "POST";
                        // get the stream object that holds request stream.
                        Stream stream = myWebRequest.GetRequestStream();
                               stream.Write(buffer, 0, buffer.Length);
                               stream.Close();
        
                        //Sends a web request and wait for response.
                        try
                        {
                            WebResponse webResponse = myWebRequest.GetResponse();
                            //get Stream Data from the response
                            Stream respData = webResponse.GetResponseStream();
                            //read the response from stream.
                            StreamReader streamReader = new StreamReader(respData);
                            string name;
                            StringBuilder str = new StringBuilder();
                            while ((name = streamReader.ReadLine()) != null)
                            {
                                str.Append(name); // Add to stringbuider when response contains multple lines data
                           }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-31
          • 1970-01-01
          • 2011-06-24
          相关资源
          最近更新 更多