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

后端 未结 5 447
南方客
南方客 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 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();
    

提交回复
热议问题