简体   繁体   English

如何通过HTTP传输图像

[英]How to transfer an image over http

I am trying to create a proxy, text based requests get processed(js, css, html) properly. 我正在尝试创建代理,基于文本的请求得到正确处理(js,css,html)。 But when i try to load in an image i get the message that the image contains errors. 但是,当我尝试加载图像时,我得到该图像包含错误的消息。

I have tried multiple ways to send this over http but none of them have worked yet. 我尝试了多种方法来通过HTTP发送此消息,但是它们都没有起作用。 Here is the relevant code 这是相关的代码

 try
        {
            StringBuilder responseString = new StringBuilder();
            HttpWebRequest clientRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)clientRequest.GetResponse();
            string headers = response.Headers.ToString();
            string contentType = response.Headers.Get("content-type");
            var encoding = ASCIIEncoding.ASCII;
            if (contentType.IndexOf("image") > -1)
            {
                using (BinaryReader stream = new BinaryReader(response.GetResponseStream()))
                {
                    var bytes = new byte[1024];
                    while (true)
                    {
                        var n = stream.Read(bytes, 0, bytes.Length);
                        if (n == 0)
                        {
                            break;
                        }
                        responseString.Append(bytes);
                    }
                    return "HTTP/1.1 200 \n" + headers + responseString.ToString();
                }
            }
            else
            {
                using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
                {

                    return "HTTP/1.1 200 \n" + headers + reader.ReadToEnd();
                } 
            }
        catch
        {
            addToList("Request failed");
            return "Request failed";
        }
    }

If possible i would prefer to keep the http response string so that I send it over the already existing NetworkStream. 如果可能的话,我希望保留http响应字符串,以便我通过现有的NetworkStream发送它。

The solution was to stream the response directly to the client and not convert it to a string first. 解决方案是将响应直接流式传输到客户端,而不先将其转换为字符串。 The headers are sent in a string before. 标头之前以字符串发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM