How to post data to specific URL using WebClient in C#

后端 未结 8 1535
深忆病人
深忆病人 2020-11-22 07:12

I need to use \"HTTP Post\" with WebClient to post some data to a specific URL I have.

Now, I know this can be accomplished with WebRequest but for some reasons I wa

相关标签:
8条回答
  • 2020-11-22 08:06

    Using WebClient.UploadString or WebClient.UploadData you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.

    byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
                    System.Text.Encoding.ASCII.GetBytes("field1=value1&field2=value2") );
     
    string sret = System.Text.Encoding.ASCII.GetString(bret);
    

    More: http://www.daveamenta.com/2008-05/c-webclient-usage/

    0 讨论(0)
  • 2020-11-22 08:14

    Using simple client.UploadString(adress, content); normally works fine but I think it should be remembered that a WebException will be thrown if not a HTTP successful status code is returned. I usually handle it like this to print any exception message the remote server is returning:

    try
    {
        postResult = client.UploadString(address, content);
    }
    catch (WebException ex)
    {
        String responseFromServer = ex.Message.ToString() + " ";
        if (ex.Response != null)
        {
            using (WebResponse response = ex.Response)
            {
                Stream dataRs = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(dataRs))
                {
                    responseFromServer += reader.ReadToEnd();
                    _log.Error("Server Response: " + responseFromServer);
                }
            }
        }
        throw;
    }
    
    0 讨论(0)
提交回复
热议问题