HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择
HttpWebRequest定义:
eg: string url="https://www.baidu.com";
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
HttpWebRequest httpRequest=(HttpWebRequest)HttpWebRequest.Create(url);
// 参数赋值
X509Certificate2 cerCaiShang = new X509Certificate2(p12certfile, cerpassword);
if (!isHttp)
{
httpRequest.ClientCertificates.Add(cerCaiShang);
}
httpRequest.Method="POST";
httpRequest.ContentType="application/json";
httpRequest.Headers.Add(key,value);
httpRequest.Refer=null;
httpRequest.AllowAutoRedirect=true;
httpRequest.UserAgent="";
httpRequest.Accept="*/*";
// 如果请求方式是Http 还需要加上 httpRequest.ServicePoint.Expect100Continue=false;
// 如果请求方式不是GET,
// Stream requestStem=httpRequest.GetRequestStream();
//StreamWriter sw=new StreamWriter(requestStem);
// sw.Write(body); // body 为json格式
//sw.Close();
// 响应
HttpWebResponse hhtpResponse=(HttpWebResponse)httpWebRequest.GetResponse();
Stream receiveStream=httpResponse.GetResponseStream();
string result=string.empty();
int statusCode=0;
using(StreamReader sr=new StreamReader(receiveStream)){
result=sr.ReadToEnd();
}
statusCode=(int)httpResponse.StatusCode;