我试图打开与服务器的连接并获取响应正文,这是一个图像。我想将其保存到Image
,然后将其显示在PictureBox
中。这是我的代码:
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);
}
我明白了:
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
但我总是得到WebException
。我是C#的新手,我想知道这里有什么问题。感谢。
答案 0 :(得分:2)
试试这个
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);
}