C# - Getting the response body from a 403 error

后端 未结 2 1537
北海茫月
北海茫月 2020-12-03 08:16

I\'m receiving a 403 error when requesting data from a URL. This is expected and I\'m not asking how to correct it.
When pasting this URL directly into my browser, I g

相关标签:
2条回答
  • 2020-12-03 08:45

    This worked For me..

    HttpWebResponse httpResponse;
                try
                {
                    httpResponse = (HttpWebResponse)httpReq.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        result = streamReader.ReadToEnd();
                    }
                }
                catch (WebException e)
                {
                    Console.WriteLine("This program is expected to throw WebException on successful run." +
                                        "\n\nException Message :" + e.Message);
                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                        Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                        using (Stream data = e.Response.GetResponseStream())
                        using (var reader = new StreamReader(data))
                        {
                            string text = reader.ReadToEnd();
                            Console.WriteLine(text);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
    
    0 讨论(0)
  • 2020-12-03 08:47

    You're looking for the WebException.Response property:

    catch(WebException ex)
    {
         var response = (HttpWebResponse)ex.Response;
    }
    
    0 讨论(0)
提交回复
热议问题