0

I'm trying to open a connection to a server and get the response body, which is an image. I want to save it to Image, and later display it in the PictureBox. Here is my code:

try
    {
        var response = WebRequest.Create(String.Format(url + "?t=webwx&_={0}", timestamp));
        var stream = response.GetRequestStream();
        Image image = Image.FromStream(stream);
        qe_img.Image = image;
        qe_img.Height = image.Height;
        qe_img.Width = image.Width;
     } catch (Exception e)
     {
        Console.WriteLine(e);
     }

I get:

Exception thrown: 'System.Net.ProtocolViolationException' in System.dll
System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
   at System.Net.HttpWebRequest.CheckProtocol(Boolean onRequestStream)
   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()
   at WindowsFormsApplication1.Form1.showQRImage() in c:\users\morgan\documents\visual studio 2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 70

But I always get a WebException. I'm new to C#, I wonder what is wrong here. Thanks.

J Freebird
  • 3,664
  • 7
  • 46
  • 81
  • 1
    Wrap your code in a try--catch block and paste the exception here. And also instead of using response.ResponseStream you need to call response.GetResponseStream() – qamar Jan 06 '16 at 06:06
  • Try getting Http code from exception example:http://stackoverflow.com/questions/3614034/system-net-webexception-http-status-code – elrado Jan 06 '16 at 06:09
  • @qamar Please see the edited code. – J Freebird Jan 06 '16 at 06:25
  • Try putting url from your Create() method into a IE and see if it works manually. I suspect the request is returning more than just the image. You can vailidate this by looking at the webpage returned in the IE by using menu : Source. You will need to find the tag that contains the image and extract the image from the html returned results. – jdweng Jan 06 '16 at 06:36
  • I think you url missing something or inalid. Can you paste the value of Url variable here? – qamar Jan 06 '16 at 08:16

1 Answers1

2

Try this

 try
            {
                var request = WebRequest.Create(String.Format(url + "?t=webwx&_={0}", timestamp));

                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        Image image = Image.FromStream(stream);
                        qe_img.Image = image;
                        qe_img.Height = image.Height;
                        qe_img.Width = image.Width;


                    }
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
santosh singh
  • 27,666
  • 26
  • 83
  • 129