How to use WebRequest to POST some data and read response?

后端 未结 5 435
南方客
南方客 2021-02-01 06:03

Need to have the server make a POST to an API, how do I add POST values to a WebRequest object and how do I send it and get the response (it will be a string) out?

I nee

相关标签:
5条回答
  • 2021-02-01 06:45

    Below is the code that read the data from the text file and sends it to the handler for processing and receive the response data from the handler and read it and store the data in the string builder class

     //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;
                    }
    
    0 讨论(0)
  • 2021-02-01 06:56

    From 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 ();
    

    Take into account that the information must be sent in the format key1=value1&key2=value2

    0 讨论(0)
  • 2021-02-01 06:56

    A more powerful and flexible example can be found here: C# File Upload with form fields, cookies and headers

    0 讨论(0)
  • 2021-02-01 07:00

    Here's an example of posting to a web service using the HttpWebRequest and HttpWebResponse objects.

    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();
    
    0 讨论(0)
  • 2021-02-01 07:05

    Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

    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());
    }
    
    0 讨论(0)
提交回复
热议问题