稍微修改了点
public static string CollectHtml(string targetUrl, string sendContent, RequestParameters reqParam)
{
string html = string.Empty;
Stream stream = null;
StreamReader sr = null;
Stream reqStream = null;
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
byte[] bs = Encoding.GetEncoding(GetEnumDescription<EncodingType>(reqParam.sendEncoding)).GetBytes(sendContent);
switch (reqParam.reqMethod)
{
case ReqMethod.Post:
request = (HttpWebRequest)WebRequest.Create(targetUrl);
request.Method = reqParam.reqMethod.ToString();
request.ContentLength = bs.Length;
request.UserAgent = reqParam.reqUserAgent;
request.ContentType = GetEnumDescription<ReqContentType>(reqParam.reqContentType);
request.Accept = reqParam.reqAccept;
break;
case ReqMethod.Get:
request = (HttpWebRequest)WebRequest.Create(targetUrl + (sendContent == "" ? "" : "?") + sendContent);
request.Method = reqParam.reqMethod.ToString();
request.ContentType = reqParam.reqContentType.ToString();
break;
default:
break;
}
if (bs.Length > 0 && reqParam.reqMethod == ReqMethod.Post)
{
reqStream = request.GetRequestStream();
reqStream.Write(bs, 0, bs.Length);
}
if (request != null)
response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
sr = new StreamReader(stream, Encoding.GetEncoding(GetEnumDescription<EncodingType>(reqParam.receivEncoding)));
html = sr.ReadToEnd();
}
catch (WebException wEx)
{
response = (HttpWebResponse)wEx.Response;
stream = response.GetResponseStream();
sr = new StreamReader(stream, Encoding.GetEncoding(GetEnumDescription<EncodingType>(reqParam.receivEncoding)));
html = sr.ReadToEnd();
}
finally
{
if (response != null)
{
response.Close();
}
if (stream != null)
{
stream.Dispose();
}
if (sr != null)
{
sr.Dispose();
}
if (reqStream != null)
{
reqStream.Dispose();
}
if (request != null)
{
request.Abort();
}
}
return html;
}
public struct RequestParameters
{
public EncodingType sendEncoding
{ get; set; }
public EncodingType receivEncoding
{ get; set; }
public ReqMethod reqMethod
{ get; set; }
public string reqUserAgent
{
get { return "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"; }
}
public ReqContentType reqContentType
{ get; set; }
public string reqAccept
{
get { return "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*"; }
}
}
public enum EncodingType
{
GB2312,
GBK,
[Description("UTF-8")]
UTF8
}
public enum ReqMethod
{
Post, Get
}
public enum ReqContentType
{
[Description("application/x-www-form-urlencod")]
Default,
[Description("image/jpeg")]
Image,
[Description("application/json")]
Json,
[Description("text/plain")]
Text,
[Description("text/xml")]
Xml
}