Sending POST data with C#

喜夏-厌秋 提交于 2019-11-29 07:54:05
Geek

I realise this is an old question but thought I would provide an answer with correct usage of using statements so the closing of connections is done without the need of calling 'Close'. Also the webrequest can be declared within the scope of the SendPost method.

public string SendPost(string url, string postData)
{
    string webpageContent = string.Empty;

    try
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.ContentLength = byteArray.Length;

        using (Stream webpageStream = webRequest.GetRequestStream())
        {
            webpageStream.Write(byteArray, 0, byteArray.Length);
        }

        using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
        {
            using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
            {
                webpageContent = reader.ReadToEnd();
            }
        }
    }
    catch (Exception ex)
    {
        //throw or return an appropriate response/exception
    }

    return webpageContent;
}

This is also following this answer https://stackoverflow.com/a/336420/453798

Hope this helps

You have a logic error in your code:

webpageStream.Close();

webpageReader = new StreamReader(webpageStream);

You're closing the stream, then trying to read from it. Once a stream is closed, it's effectively dead.

The more fundamental problem is that you're trying to write your request to the response, which is not only nonsensical, but also impossible! What you want to do is write to the request stream, then get the response like this:

webpageStream = _webRequest.GetRequestStream();
webpageStream.Write(byteArray, 0, byteArray.Length);
webpageStream.Close();

webpageReader = new StreamReader(_webRequest.GetResponse().GetResponseStream());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!