|
楼主 |
发表于 2013-11-4 10:50:40
|
显示全部楼层
public static string postMethod(string urlAddr, string postStr, ref CookieContainer cookies, string IP = "", int port = 0, string refer = "")
{
string htmlResource = "";
if (postStr == null || postStr == "")
{
Console.WriteLine("post data is empty!");
return htmlResource;
}
if (urlAddr == null || urlAddr == "")
{
Console.WriteLine("url addr is empty!");
return htmlResource;
}
HttpWebResponse response = null;
HttpWebRequest request = null;
//这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
try
{
request = (HttpWebRequest)WebRequest.Create(urlAddr);
request.ClientCertificates.Add(new X509Certificate("cerify.cer"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//显示异常信息
return htmlResource;
}
if (IP != "" && port > 0)
{
WebProxy proxyObject = new WebProxy(IP, port);//str为IP地址 port为端口号
//建议连接
proxyObject.Credentials = new NetworkCredential("","");
proxyObject.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxyObject;
}
byte[] byteData = Encoding.UTF8.GetBytes(postStr);
request.Timeout = 300000;
request.Method = "POST";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0";
request.ContentType = contentType;
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
if (refer != "")
{
request.Referer = refer;
}
request.ContentLength = byteData.Length;
request.CookieContainer = cookies;
Stream stream = request.GetRequestStream();
stream.Write(byteData, 0, byteData.Length);
stream.Close();
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//显示异常信息
return htmlResource;
}
////查看是否成功
if (response.StatusCode != HttpStatusCode.OK)
{
MessageBox.Show("http response is error!");//显示异常信息
}
///获取返回的结果
try
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
htmlResource = reader.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//显示异常信息
return htmlResource;
}
cookies.Add(response.Cookies);
return htmlResource;
}
用这段代码不会保持,但是用HttpHelper类还是报之前那个错!
|
|