c#从网站下载PNG文件并在请求中发送cookie?

时间:2013-07-23 20:39:11

标签: c# http httpwebrequest png tcpclient

您好我正在尝试从网站下载.PNG图片,但我需要在请求中发送我的标题来下载图片。我的最终目标是将图像直接加载到Stream中,而不是将其保存到文件中。

这是我得到Image的HTML的代码:

public string Request(string type, string page, string data = "", string referer = "")
{
    using(TcpClient tcp = new TcpClient(this.SiteName, this.Port))
    {
        byte[] headers = Encoding.Default.GetBytes(this.MakeHeaders(type, page, referer, data));
        using (NetworkStream ns = tcp.GetStream())
        {
            ns.Write(headers, 0, headers.Length);
            using (StreamReader sr = new StreamReader(ns, Encoding.Default))
            {
                string html = sr.ReadToEnd();
                return html;
            }
        }
    } 
}

我发送的标题如下所示:

GET /image.php HTTP/1.1
Host: greymatter.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Connection: close
Cache-Control: max-age=0
Cookie: PHPSESSID=s0v17eafosj5ctb5v6keu3lh57; __cfduid=d10aef4fcfd052e1f59fba9832cedf4491374611636

我本地保存的PNG文件以:

开头
67f
‰PNG

保存的PNG文件已损坏 - 无法查看!我不明白为什么会这样?

1 个答案:

答案 0 :(得分:1)

请求是针对php文档的请求。网站的各个资产将单独下载。因此,单个TCP请求可能无法涵盖您打算执行的操作。 我建议Fiddler查看为请求网页而进行的调用。

我也会考虑使用Image.FromStream() 将流转换为png。 (只是一个pref。使用字节数组和数据流对我来说一直特别容易出错。)

它使用了这样的东西。

byte[] imageData = MyRequestFunction(Url); //MyRequestFunction function from here
MemoryStream stream = new MemoryStream(imageData);
Image img = Image.FromStream(stream);
stream.Close();

另外web requests是为了你正在做的事情。 这个例子可能会有所帮助 How to read picture from URL and show it on my page