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

后端 未结 5 530
南方客
南方客 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;
                    }
    

提交回复
热议问题