HttpHandler WebRequest内容类型不像浏览器那样工作

时间:2014-12-25 14:43:10

标签: c# asp.net .net httpwebrequest webrequest

我创建了一个使用WebRequest的方法。

网址为:http://demo.boundlessgeo.com/geoserver/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&LAYERS=ne%3Ane&WIDTH=256&HEIGHT=256&CRS=EPSG%3A3857&STYLES=&BBOX=-80150033.37115698%2C0%2C-60112525.02836773%2C20037508.342789244

此网址会恢复png图像。当我在浏览器上访问时,它出现了。

我正在使用c#WebClient对象发送url并返回

的请求
HttpWebRequest webRequest;
webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
webRequest.Method = "GET";

HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse();

if (response.StatusCode.ToString().ToLower() == "ok")
{
    context.Response.ContentType = response.ContentType;
    StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
    context.Response.Write(reader.ReadToEnd());
}

这将返回如下编码文本:

�PNG    
IHDR\r�f��IDATx^�}�^IU盦�ǖ��VP�nő��%�\i��4N���yN۹N��N3s�V�{���d�\�x�6�H����B h�@�4   ��A9�����N=�T�]{?�I���Q��w��Z�j�U�V�����+���۱��-Vavvw2_T�/V�x�_�X1�}Պ�N+\�Gyv�����Z�����,�^�b���)���T~UkU�,�|��X�\�6�w��|��OoS�k����X�znm'��|��������X���y6�$]u���uQ]��̈�l�xEQ��

你有什么问题?

1 个答案:

答案 0 :(得分:0)

        context.Response.ContentType = response.ContentType;

        using (WebResponse response = webRequest.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (Stream outputStream = context.Response.OutputStream)
                {
                    int cnt = 0;
                    byte[] buffer = new byte[4096];
                    do
                    {
                        cnt = responseStream.Read(buffer, 0, buffer.Length);
                        outputStream.Write(buffer, 0, cnt);
                    } while(cnt != 0);
                }
            }
        }