Web 请求的通用响应

发布于 2025-01-02 21:40:37 字数 2085 浏览 0 评论 0原文

我刚刚编写了一个 C# Lib 来安全地处理 WebRequest(可以在打开代码的情况下找到该库,此处

)此刻,我的 GET 方法将始终返回一个字符串作为响应,但有时就像从站点获取验证码时一样,它需要返回一个位图。

我该怎么做?我如何使用某种类型使此 Get 请求尽可能通用,从而使任何人都可以选择它将收到的响应类型。

改进问题:

这是我现在尝试的。它无法编译,因为它说它无法将这一行上的 String 转换为类型 T

response = (T) new StreamReader(resp.GetResponseStream()).ReadToEnd();

这是我的新方法:

public T Get <T> (string url)
    {
        T response = default(T);

        // Checking for empty url
        if (String.IsNullOrEmpty(url))
        {
            throw new Exception("URL para o Request não foi configurada ou é nula.");
        }

        try
        {
            // Re-Creating Request Object to avoid exceptions
            m_HttpWebRequest = WebRequest.Create (url) as HttpWebRequest;

            m_HttpWebRequest.CookieContainer              = m_CookieJar;
            m_HttpWebRequest.Method                       = "GET";
            m_HttpWebRequest.UserAgent                    = m_userAgent;
            m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
            m_HttpWebRequest.Timeout                      = m_timeout;
            m_HttpWebRequest.ContentType                  = m_contentType;
            m_HttpWebRequest.Referer                      = m_referer;
            m_HttpWebRequest.AllowAutoRedirect            = m_allowAutoRedirect;

            if (!String.IsNullOrEmpty(m_host))
            {
                m_HttpWebRequest.Host = m_host;
            }

            // Execute web request and wait for response
            using (HttpWebResponse resp = (HttpWebResponse) m_HttpWebRequest.GetResponse())
            {
              response = (T) new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            m_error  = ex.ToString();

            if (m_logOnError)
                LogWriter.Error(ex);
        }

        return response;
    } 

I just wrote a C# Lib to handle WebRequests safely (Which can be found, with the code open , Here)

At the moment, my GET Method will always return a string as the response, but sometimes like when fetching captchas from a site, it will need to return a Bitmap instead.

How do i do This ? How do i use a sort of Type to make this Get request as generic as possible, making possible for anyone to choose the type of response it will receive.

Improving Question:

This is what i tried now. It does not compiles because it says it can't convert a String to a Type T on this line :

response = (T) new StreamReader(resp.GetResponseStream()).ReadToEnd();

This is my new Method :

public T Get <T> (string url)
    {
        T response = default(T);

        // Checking for empty url
        if (String.IsNullOrEmpty(url))
        {
            throw new Exception("URL para o Request não foi configurada ou é nula.");
        }

        try
        {
            // Re-Creating Request Object to avoid exceptions
            m_HttpWebRequest = WebRequest.Create (url) as HttpWebRequest;

            m_HttpWebRequest.CookieContainer              = m_CookieJar;
            m_HttpWebRequest.Method                       = "GET";
            m_HttpWebRequest.UserAgent                    = m_userAgent;
            m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
            m_HttpWebRequest.Timeout                      = m_timeout;
            m_HttpWebRequest.ContentType                  = m_contentType;
            m_HttpWebRequest.Referer                      = m_referer;
            m_HttpWebRequest.AllowAutoRedirect            = m_allowAutoRedirect;

            if (!String.IsNullOrEmpty(m_host))
            {
                m_HttpWebRequest.Host = m_host;
            }

            // Execute web request and wait for response
            using (HttpWebResponse resp = (HttpWebResponse) m_HttpWebRequest.GetResponse())
            {
              response = (T) new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            m_error  = ex.ToString();

            if (m_logOnError)
                LogWriter.Error(ex);
        }

        return response;
    } 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

说谎友 2025-01-09 21:40:38

方法 1:

您可以使用 Base64 对位图进行编码。下面是一个向您展示如何操作的示例: http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx

这样,你总是返回一个字符串,即使您返回一个图像:-)

方法 2:

您可以将类型信息附加到 URL,如下所示:

GET /mypage/whatever/api?x=3&y=4&t=image

Approach 1:

You could encode the bitmap using Base64. Here's an example that shows you how: http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx

This way, you always return a string, even when you return an image :-)

Approach 2:

You could append type info to the URL, like so:

GET /mypage/whatever/api?x=3&y=4&t=image
你如我软肋 2025-01-09 21:40:38

我建议你已经差不多完成了。如果响应恰好是位图,那么显示或解释该数据的方式就很重要。

归根结底,您拥有的是一组字节,其中包含从 get 方法返回的字符串,无论该内容是字符串还是图像。

您可以(例如,未测试的代码)将此字符串转换回字节,然后转换为位图。

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(responseString);

TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap1 = (Bitmap) tc.ConvertFrom(bytes);

向用户显示数据时,如果在 Web 浏览器中,则可以通过响应标头控制浏览器应如何处理响应的解释:

Response.AddHeader("Content-Disposition", "Attachment; filename=Report.xls ”);
Response.ContentType = "application/vnd.ms-excel";

I would suggest that you are most of the way there. If the response happens to be a bitmap, it's how you display or interpret that data that matters.

At the end of the day, what you have is a set of bytes which comprises the string you return from your get method, regardless of whether that content is a string or an image.

You could (for example, code not tested) convert this string back to bytes, and then to a bitmap.

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(responseString);

TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap1 = (Bitmap) tc.ConvertFrom(bytes);

When displaying data to a user, if in a web browser, the interpretation of what the browser should do with the response can be controlled by the response headers:

Response.AddHeader("Content-Disposition", "Attachment; filename=Report.xls");
Response.ContentType = "application/vnd.ms-excel";

北座城市 2025-01-09 21:40:37

您可以使用泛型,也可以只传递所需对象的Type

   private T Get<T>()
    {
        Type t_type = typeof(T);

        if (t_type == typeof(string))
        {
            // return string
        }
        else if (t_type == typeof(Bitmap))
        {
            // return bitmap
        }
    }

然后像这样称呼它。

Bitmap b = response.Get<Bitmap>();

You can use generics, or you can just pass the Type of the object you want.

   private T Get<T>()
    {
        Type t_type = typeof(T);

        if (t_type == typeof(string))
        {
            // return string
        }
        else if (t_type == typeof(Bitmap))
        {
            // return bitmap
        }
    }

Then call it like so.

Bitmap b = response.Get<Bitmap>();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文