(http的请求关键在于编码 )
1.第一种请求
///
/// Get请求
///
/// 请求的url
/// 请求的头部
///
public static string Get(string url, string reqHead)
{
string result = "";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add("Authorization", reqHead);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse httpWebResponse;
try
{
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (WebException e)
{
httpWebResponse = (HttpWebResponse)e.Response;
}
Stream responseStream = httpWebResponse.GetResponseStream();
using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
{
result = streamReader.ReadToEnd();
}
return result;
}
///
/// Post请求
///
/// 请求Url
/// 请求内容
/// 请求头部
///
public static string Post(string url, string reqBody, string reqHead)
{
string result = "";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", reqHead);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.UTF8.GetBytes(reqBody);
httpWebRequest.ContentLength = (long)bytes.Length;
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
HttpWebResponse httpWebResponse;
try
{
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (WebException e)
{
httpWebResponse = (HttpWebResponse)e.Response;
}
Stream responseStream = httpWebResponse.GetResponseStream();
using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
{
result = streamReader.ReadToEnd();
}
return result;
}
2.第二种方法:
///
/// get请求
///
///
///
public static string GetResponse(string url)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.9");
httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
httpClient.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
System.Net.Http.HttpResponseMessage response = httpClient.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
///
/// post请求
///
///
/// post数据
///
public static string PostResponse(string url, string postData)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
System.Net.Http.HttpContent httpContent = new System.Net.Http.StringContent(postData, Encoding.UTF8, "application/json");
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.9");
httpClient.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
3.第三种写法:
//表明身份的作用域,这里模拟浏览器IE
public static string _UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
public static CookieContainer cookieC = new CookieContainer();
public static string cookiestr = "";
///
/// Get请求
///
///
///
public static string GetHtml(string url)
{
//处理HttpWebRequest访问https有安全证书的问题( 请求被中止: 未能创建 SSL/TLS 安全通道。)
//ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieC;
request.Headers.Add("Cookie:" + cookiestr);
//Get请求方式
request.Method = "GET";
request.Headers.Add("Access-Control-Allow-Origin", "*");
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
request.KeepAlive = true;
request.Host = "www.thaievisa.go.th";
request.Referer = "https://www.thaievisa.go.th/Home/Login";
//request.ContentType = "text/html; charset=utf-8";
request.UserAgent = _UserAgent;
String strValue = ""; //strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
if (string.IsNullOrEmpty(cookiestr))
{
cookiestr = request.CookieContainer.GetCookieHeader(request.RequestUri) + ";" + cookiestr;
}
request.Headers.Add("Cookie:" + cookiestr);
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream sm = response.GetResponseStream();
//使用了gzip压缩流编码时的处理
var ce = response.ContentEncoding;
if (ce.ToLower() == "gzip")
{
sm = new GZipStream(sm, CompressionMode.Decompress);
}
StreamReader streamReader = new StreamReader(sm, System.Text.Encoding.UTF8);
strValue = streamReader.ReadToEnd();
streamReader.Close();
sm.Close();
request.Abort();
response.Close();
return strValue;
}
///
/// Post请求
///
/// 请求的地址
/// 提交数据
///
public static string PostHtml(string url, string data = "")
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieC;
request.Headers.Add("Cookie:" + cookiestr);
//Post请求方式
request.Method = "POST";
request.Headers.Add("Access-Control-Allow-Origin", "*");
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
request.KeepAlive = true;
request.Host = "www.thaievisa.go.th";
request.Headers.Add("Origin", "https://www.thaievisa.go.th");
request.Referer = "https://www.thaievisa.go.th/Home/Login";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.UserAgent = _UserAgent;
byte[] payload;
//将Json字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(data);
//设置请求的ContentLength
request.ContentLength = payload.Length;
//发送请求,获得请求流
Stream writer;
try
{
writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
}
catch (Exception)
{
writer = null;
string msg = "连接服务器失败!";
return msg;
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close(); //关闭请求流
String strValue = ""; //strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
//使用了gzip压缩流编码时的处理
var ce = response.ContentEncoding;
if (ce.ToLower() == "gzip")
{
s = new GZipStream(s, CompressionMode.Decompress);
}
StreamReader streamReader = new StreamReader(s, System.Text.Encoding.UTF8);
strValue = streamReader.ReadToEnd();
streamReader.Close();
s.Close();
request.Abort();
response.Close();
return strValue; //返回Json数据
}