|
一般自定义的404错误会输出一个404StatusCode和自定义错误页面内容,HttpHelper遇到这种情况就产生WebException错误,不能获取具体错误页面
1.4.1版本GetHtml方法 修改的代码如下
public HttpResult GetHtml(HttpItem objhttpitem)
{
//返回参数
HttpResult result = new HttpResult();
try
{
//准备参数
SetRequest(objhttpitem);
}
catch (Exception ex)
{
result = new HttpResult();
result.Cookie = string.Empty;
result.Header = null;
result.Html = ex.Message;
result.StatusDescription = "配置参数时出错:" + ex.Message;
return result;
}
try
{
#region 得到请求的response
//using (response = (HttpWebResponse)request.GetResponse())
//{
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
//这里是在发生异常时返回的错误信息
response = (HttpWebResponse)ex.Response;
}
result.StatusCode = response.StatusCode;
result.StatusDescription = response.StatusDescription;
result.Header = response.Headers;
if (response.Cookies != null) result.CookieCollection = response.Cookies;
if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
MemoryStream _stream = new MemoryStream();
//GZIIP处理
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
{
//开始读取流并设置编码方式
//new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
//.net4.0以下写法
_stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
}
else
{
//开始读取流并设置编码方式
//response.GetResponseStream().CopyTo(_stream, 10240);
//.net4.0以下写法
_stream = GetMemoryStream(response.GetResponseStream());
}
//获取Byte
byte[] RawResponse = _stream.ToArray();
_stream.Close();
//是否返回Byte类型数据
if (objhttpitem.ResultType == ResultType.Byte) result.ResultByte = RawResponse;
//从这里开始我们要无视编码了
if (encoding == null)
{
Match meta = Regex.Match(Encoding.Default.GetString(RawResponse), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
string charter = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToLower() : string.Empty;
if (charter.Length > 2)
encoding = Encoding.GetEncoding(charter.Trim().Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk"));
else
{
if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8;
else encoding = Encoding.GetEncoding(response.CharacterSet);
}
}
//得到返回的HTML
result.Html = encoding.GetString(RawResponse);
response.Close();
//}
#endregion
}
//catch (WebException ex)
//{
// //这里是在发生异常时返回的错误信息
// response = (HttpWebResponse)ex.Response;
// result.Html = ex.Message;
// if (response != null)
// {
// result.StatusCode = response.StatusCode;
// result.StatusDescription = response.StatusDescription;
// }
//}
catch (Exception ex)
{
result.Html = ex.Message;
}
if (objhttpitem.IsToLower) result.Html = result.Html.ToLower();
return result;
}
建议在HttpItem的时候加个控制是否返回详细内容或错误信息
[i]嬠/i]
|
|