1、Get请求
使用HttpWebRequest进行Get请求:
public static string get(string url)
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
reader.Close();
myResponse.Close();
return returnXml;
}
使用HttpClient进行异步Get请求:
public static string GetData(string url,string data)
{
string strResult = "";
try
{
url = url+ "?" + data;
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
strResult = response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception)
{
throw;
}
return strResult;
}
2、Post请求
使用HttpClient 进行异步的Post请求:
/// <summary>
/// 接口调用
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string PostData(string url, string data)
{
string strResult = "";
try
{
var str = JsonConvert.SerializeObject(data);
var httpContent = new StringContent(str, Encoding.UTF8, "application/json");
//string url = GetConfigUrl(encode);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
strResult = response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception ex)
{
throw ex;
}
return strResult;
}
使用System.Net.HttpWebRequest的Post请求:
public static string sendPost(string url, string postData)
{
System.Net.HttpWebRequest webrequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
webrequest.Method = "post";
webrequest.ContentType = "application/json";
byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
webrequest.ContentLength = postdatabyte.Length;
Stream stream;
stream = webrequest.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length);
stream.Close();
using (var httpWebResponse = webrequest.GetResponse())
using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
{
String ret = responseStream.ReadToEnd();
string result = ret.ToString();
return result;
}
}
3、使用HttpWebRequest的Cookie的跨登录请求
登录获取Cookie:
CookieContainer globeCookie = new CookieContainer();
public static string DoPostLogin(string url, string data, ref CookieContainer myCookieContainer)
{
try
{
HttpWebRequest webRequest = GetWebRequest(url, "POST");
webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
webRequest.CookieContainer = myCookieContainer;
byte[] bytes = Encoding.UTF8.GetBytes(data);
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
myCookieContainer.Add(httpWebResponse.Cookies);
Encoding encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
return GetResponseAsString(httpWebResponse, encoding);
}
catch (Exception ex)
{
return ex.Message;
}
}
使用登录取到的Cookie去访问接口:
public static string DoPost(string url, string data, CookieContainer inputCookieContainer)
{
try
{
HttpWebRequest webRequest = GetWebRequest(url, "POST");
webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
webRequest.CookieContainer = inputCookieContainer;
byte[] bytes = Encoding.UTF8.GetBytes(data);
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
Encoding encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
return GetResponseAsString(httpWebResponse, encoding);
}
catch (Exception ex)
{
return ex.Message;
}
}
读取HttpWebResponse
public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
Stream responseStream = null;
StreamReader reader = null;
string str;
try
{
responseStream = rsp.GetResponseStream();
reader = new StreamReader(responseStream, encoding);
str = reader.ReadToEnd();
}
finally
{
if (reader != null)
{
reader.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
if (rsp != null)
{
rsp.Close();
}
}
return str;
}
4、请求form表单文章来源:https://www.toymoban.com/news/detail-505078.html
public static string PostDS(string url, string data, string ticket)
{
string result = "";
try
{
string SendMessageAddress = url;//请求链接
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SendMessageAddress);
request.Method = "POST";
request.AllowAutoRedirect = true;
//request.Timeout = 20 * 1000;
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", ticket);
//string PostData = "a=1&b=2";//请求参数格式
string PostData = data;//请求参数
byte[] byteArray = Encoding.Default.GetBytes(PostData);
request.ContentLength = byteArray.Length;
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream rspStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8))
{
result = reader.ReadToEnd();
rspStream.Close();
}
response.Close();
}
catch (Exception ex)
{
result = "false";
}
return result;
}
5、创建https的HttpWebRequest请求文章来源地址https://www.toymoban.com/news/detail-505078.html
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
public static HttpWebRequest GetWebRequest(string url, string method)
{
HttpWebRequest request;
if (url.Contains("https"))
{
//用于验证服务器证书的回调
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
request = (HttpWebRequest)WebRequest.Create(url);
}
request.Method = method;
request.Timeout = 0x186a0;
return request;
}
到了这里,关于C#——HTTP请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!