Web 请求的通用响应
我刚刚编写了一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
方法 1:
您可以使用 Base64 对位图进行编码。下面是一个向您展示如何操作的示例: http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx
这样,你总是返回一个字符串,即使您返回一个图像:-)
方法 2:
您可以将类型信息附加到 URL,如下所示:
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 方法返回的字符串,无论该内容是字符串还是图像。
您可以(例如,未测试的代码)将此字符串转换回字节,然后转换为位图。
向用户显示数据时,如果在 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.
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";
您可以使用泛型,也可以只传递所需对象的
Type
。然后像这样称呼它。
You can use generics, or you can just pass the
Type
of the object you want.Then call it like so.