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

后端 未结 8 1682
深忆病人
深忆病人 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: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;
    }
    

提交回复
热议问题