POST请求
/// <summary>
/// POST请求获取信息
/// </summary>
/// <param name="url"></param>
/// <param name="paramData"></param>
/// <returns></returns>
public string POST(string url, string paramData, int timeout = , List<System.Net.Cookie> cookies = null)
{
string ret = string.Empty;
try
{
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate); //rcvc;
webReq.ProtocolVersion = HttpVersion.Version10;
}
SetProxy(ref webReq);
webReq.Method = "POST";
webReq.ContentType = "application/json; charset=utf-8";
webReq.ServicePoint.Expect100Continue = false;
//webReq.ContentType = "text/html;charset=utf-8";
webReq.Timeout = timeout;
webReq.ContentLength = byteArray.Length; if (!string.IsNullOrEmpty(UserAgent))
webReq.UserAgent = UserAgent;
if (cookies != null && cookies.Count > )
{
webReq.CookieContainer = new CookieContainer(); string host = new Uri(url).Host;
foreach (System.Net.Cookie c in cookies)
{
c.Domain = host;
webReq.CookieContainer.Add(c);
}
}
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, , byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
}
catch (Exception ex)
{
ClassLoger.Error(ex, "HttpUtils/POST", url);
throw ex;
}
return ret;
}
GET请求
/// <summary>
/// GET请求获取信息
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string GET(string url, int timeout = , List<System.Net.Cookie> cookies = null)
{
string ret = string.Empty;
try
{
HttpWebRequest web = (HttpWebRequest)HttpWebRequest.Create(url);
if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate); //rcvc;
web.ProtocolVersion = HttpVersion.Version10;
}
SetProxy(ref web);
web.Method = "GET";
web.Timeout = timeout;
if (!string.IsNullOrEmpty(UserAgent))
web.UserAgent = UserAgent;
if (cookies != null && cookies.Count > )
{
web.CookieContainer = new CookieContainer(); string host = new Uri(url).Host;
foreach (System.Net.Cookie c in cookies)
{
c.Domain = host;
web.CookieContainer.Add(c);
}
}
HttpWebResponse res = (HttpWebResponse)web.GetResponse();
Stream s = res.GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.UTF8);
ret = sr.ReadToEnd();
sr.Close();
res.Close();
s.Close();
//ClassLoger.Error("HttpUtils/GET",url+" "+ ret);
}
catch (Exception ex)
{
ClassLoger.Error(ex, "HttpUtils/GET", url);
throw ex;
}
return ret;
}