【问题标题】:c# Downloading PNG file from website and sending cookies in Request?c#从网站下载PNG文件并在请求中发送cookie?
【发布时间】:2013-07-24 05:04:51
【问题描述】:

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

这是我获取图像 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 文件已损坏 - 无法查看!我不明白为什么会这样?

【问题讨论】:

  • 实际请求是否以php结尾?如果是这样,那么我认为这是您的一个问题开始的地方。 png 的请求标头看起来像“GET /careers/Img/testimonial-quote.png HTTP/1.1”

标签: c# http httpwebrequest png tcpclient


【解决方案1】:

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

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

它使用了类似的东西。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 2017-07-11
    相关资源
    最近更新 更多