HttpHelper
public static class HttpHelper
{
const String POST = "Post";
const String ACCEPT= "text/html, application/xhtml+xml, */*";
const String CONTENT_TYPE="application/x-www-form-urlencoded";
const Int16 TIMEOUT = 30 * 1000;
public const String EXCEPTION_DESCPTION = "ERROR";
const String DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
///<summary>
///采用http协议访问网络
///</summary>
///<param name="URL">url地址</param>
///<param name="strPostdata">发送的数据</param>
///<returns></returns>
public static String Post(string Url, string strPostdata, string strEncoding = "")
{
Encoding recieveEncoding = Encoding.Default;
if(!String.IsNullOrEmpty (strEncoding ))
{
recieveEncoding = System.Text.Encoding.GetEncoding(strEncoding);
}
return Post(Url, strPostdata, recieveEncoding);
}
public static String Post(string Url, string strPostdata, Encoding recieveEncoding)
{
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = POST;
request.Accept = ACCEPT;
request.ContentType = CONTENT_TYPE;
request.Timeout = TIMEOUT;
request.Proxy = null;
request.UserAgent = DefaultUserAgent;
byte[] buffer = encoding.GetBytes(strPostdata);
request.ContentLength = buffer.Length;
try
{
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), recieveEncoding))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
return EXCEPTION_DESCPTION;
}
}
public static string Get(string Url, string strEncoding = "")
{
Encoding recieveEncoding = Encoding.Default;
if (!String.IsNullOrEmpty(strEncoding))
{
recieveEncoding = System.Text.Encoding.GetEncoding(strEncoding);
}
return Get(Url, recieveEncoding);
}
public static string Get(string Url, Encoding recieveEncoding)
{
try
{
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
// Get the response instance.
wReq.Proxy = null;
wReq.Timeout = TIMEOUT;
System.Net.WebResponse wResp = wReq.GetResponse();
System.IO.Stream respStream = wResp.GetResponseStream();
// Dim reader As StreamReader = New StreamReader(respStream)
using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, recieveEncoding))
{
return reader.ReadToEnd();
}
}
catch (System.Exception ex)
{
//errorMsg = ex.Message;
return EXCEPTION_DESCPTION;
}
}
}