Http请求基本方法
1.Http请求基本方法
/// <summary>
/// Http请求基本方法
/// </summary>
/// <param name="content"></param>
/// <param name="url"></param>
/// <param name="method"></param>
/// <param name="data"></param>
/// <param name="referer"></param>
/// <param name="contentTp"></param>
/// <param name="headers"></param>
/// <returns></returns>
public bool Request(ref string content, string url, string method, byte[] data, string referer = "", string contentTp = "", NameValueCollection headers = null)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = method;
request.Timeout = Timeout;
request.AllowAutoRedirect = false;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60";
request.Headers.Add("Accept-Language", "zh-TW,en;q=0.8,zh-CN;q=0.7,zh;q=0.5,zh-HK;q=0.3,en-US;q=0.2");
request.Headers.Add("Accept-Encoding", "gzip,deflate"); /// gzip 如何判断并且解码 测试是否可以暂时先注释 https://www.crifan.com/set_accept_encoding_header_to_gzip_deflate_return_messy_code/
request.AutomaticDecompression = DecompressionMethods.GZip;
request.Headers.Add("Cache-Control", "max-age=0");
request.KeepAlive = true; if (Proxy != null)
{
request.Proxy = Proxy;
} if (!string.IsNullOrEmpty(referer))
{
request.Referer = referer;
} if (headers != null && headers.Count > 0)
{
foreach (string key in headers.AllKeys)
{
request.Headers.Add(key, headers[key]);
}
} if (cookieContainer == null)
{
cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
}
else
{
request.CookieContainer = cookieContainer;
} if (method.ToLower() == "post")
{
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers.Add("Upgrade-Insecure-Requests", "1");
request.ContentType = contentTp; if (data != null && data.Length > 0)
{
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
}
else
{
request.Accept = "text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8";
} ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (headers != null && headers.Count > 0)
{
foreach (string key in headers.AllKeys)
{
response.Headers.Add(key, headers[key]);
}
} if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.RedirectMethod || response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)
{
if (response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.RedirectMethod || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)
{
string redirectUrl = GetRedirectUrl(url, response.Headers["Location"]);
return Request(ref content, redirectUrl, "GET", null, url, contentTp);
} Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream, defaultEncoding); content = streamReader.ReadToEnd();
streamReader.Close();
stream.Close();
response.Close(); return true;
}
else
{
return false;
}
}
}
catch (WebException e)
{
var res = (HttpWebResponse)e.Response; StreamReader sr = new StreamReader(res.GetResponseStream()); var strHtml = sr.ReadToEnd(); if (e.Response != null)
{
using (Stream respStream = e.Response.GetResponseStream())
{
StreamReader streamReader = new StreamReader(respStream, Encoding.UTF8);
content = streamReader.ReadToEnd();
streamReader.Close();
respStream.Close();
e.Response.Close();
}
}
return false;
}
catch (Exception e)
{
content = e.Message;
return false;
}
}
获取跳转url:
/// <summary>
/// 跳转时,获取跳转URL
/// </summary>
/// <param name="url"></param>
/// <param name="location"></param>
/// <returns></returns>
public static string GetRedirectUrl(string url, string location)
{
try
{
if (location.StartsWith("https://") || location.StartsWith("http://"))
return location;
string newUrl = url;
if (location.StartsWith("/"))
{
newUrl = url.Substring(0, url.Substring(8).IndexOf("/") + 8);
return newUrl + location;
}
else if (location.StartsWith("../"))
{
while (location.StartsWith("../"))
{
if (newUrl.IndexOf("/") > 0)
{
newUrl = newUrl.Substring(0, newUrl.LastIndexOf("/"));
}
location = location.Substring(3);
}
return newUrl + "/" + location;
}
else if (location.StartsWith("./"))
{
if (newUrl.IndexOf("/") > 0)
{
newUrl = newUrl.Substring(0, newUrl.LastIndexOf("/"));
}
location = location.Substring(2);
return newUrl + "/" + location;
}
else
{
if (newUrl.IndexOf("/") > 0)
{
newUrl = newUrl.Substring(0, newUrl.LastIndexOf("/"));
}
return newUrl + "/" + location;
}
}
catch
{
return url;
}
}
2.带文件的form提交
/// <summary>
/// 带文件的Form提交
/// </summary>
/// <param name="content"></param>
/// <param name="url"></param>
/// <param name="formData"></param>
/// <param name="referer"></param>
/// <returns></returns>
public bool FileRequest(ref string content, string url, List<FormItem> formData, string referer, string lang = "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
{
try
{
string boundary = "---------------------------255132704032490"; //+ DateTime.Now.Ticks.ToString(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.CookieContainer = cookieContainer;
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.Timeout = Timeout;
request.AllowAutoRedirect = false;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0";
request.Headers.Add("Accept-Language", lang);
request.Headers.Add("Accept-Encoding", "deflate, br");
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers.Add("Upgrade-Insecure-Requests", "1"); if (!string.IsNullOrEmpty(referer))
request.Referer = referer; if (Proxy != null)
{
request.Proxy = Proxy;
} ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; byte[] bdBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
byte[] brBytes = Encoding.UTF8.GetBytes("\r\n"); long length = bdBytes.Length; MemoryStream mStream = new MemoryStream(); foreach (var item in formData)
{
StringBuilder sb = new StringBuilder(); if (item.IsFile)
{ if (string.IsNullOrWhiteSpace(item.FilePath))
{
sb.Append($"--{boundary}\r\n");
sb.Append($"Content-Disposition: form-data; name=\"{item.Name}\"; filename=\"{item.FileName}\"\r\n");
sb.Append($"Content-Type: {item.ContentTp}");
sb.Append("\r\n");
sb.Append("\r\n");
sb.Append("\r\n");
}
else
{
if (string.IsNullOrWhiteSpace(item.FileName))
{
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(item.Name);
sb.Append("\"; filename=\"");
sb.Append(System.IO.Path.GetFileName(item.FilePath));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(item.ContentTp);
sb.Append("\r\n");
sb.Append("\r\n");
}
else
{
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(item.Name);
sb.Append("\"; filename=\"");
sb.Append(item.FileName);
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(item.ContentTp);
sb.Append("\r\n");
sb.Append("\r\n");
}
}
}
else
{
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(item.Name);
sb.Append("\"");
sb.Append("\r\n");
sb.Append("\r\n");
sb.Append(item.Value);
sb.Append("\r\n");
} string formTxt = sb.ToString(); byte[] data = Encoding.UTF8.GetBytes(formTxt); mStream.Write(data, 0, data.Length); length += data.Length; if (item.IsFile)
{
if (!string.IsNullOrWhiteSpace(item.FilePath))
{
FileStream stream = new FileStream(item.FilePath, FileMode.Open, FileAccess.Read); length += stream.Length; byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)stream.Length))]; int nRead = 0; while ((nRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
mStream.Write(buffer, 0, nRead);
} mStream.Write(brBytes, 0, brBytes.Length); length += brBytes.Length;
}
}
} /// 循环结束,需要增加结束标记 长度之前已经默认
mStream.Write(bdBytes, 0, bdBytes.Length);
mStream.Flush(); request.ContentLength = length; long n = mStream.Length; using (Stream stream = request.GetRequestStream())
{
/// 回头需要校验代码
byte[] data = mStream.GetBuffer(); stream.Write(data, 0, (int)mStream.Length);
}
HttpWebResponse res;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
response.Headers.Add("Accept-Language", lang);
string redirectUrl = GetRedirectUrl(url, response.Headers["Location"]); /// 判断是否跳转
if (response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.RedirectMethod || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)
{
var headers = new NameValueCollection();
headers.Add("Accept-Language", lang);
return Get(ref content, redirectUrl, null, referer, headers);
}
else
{
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream, System.Text.Encoding.UTF8);
content = streamReader.ReadToEnd();
streamReader.Close();
stream.Close();
}
response.Close(); return true;
}
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response; StreamReader sr = new StreamReader(res.GetResponseStream()); var strHtml = sr.ReadToEnd();
//MainForm.Instance.Console("表单提交:" + e.Message);
return false;
} }
catch
{
//MainForm.Instance.Console("表单提交:" + e.Message);
return false;
}
}
3.HTTP POST方式请求数据(带图片)
/// <summary>
/// HTTP POST方式请求数据(带图片)
/// </summary>
/// <param name="url">URL</param>
/// <param name="param">POST的数据</param>
/// <param name="fileByte">图片Byte</param>
/// <returns></returns>
public string Post(string url, IDictionary<object, object> param, byte[] fileByte)
{
try
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.UserAgent = "RK_C# 1.2";
wr.Method = "POST"; //wr.Timeout = 150000;
//wr.KeepAlive = true; //wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = null;
try
{
rs = wr.GetRequestStream();
}
catch { return "无法连接.请检查网络."; }
string responseStr = null; string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in param.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, param[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "image", "i.gif", "image/gif");//image/jpeg
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length); rs.Write(fileByte, 0, fileByte.Length); byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
rs.Write(trailer, 0, trailer.Length);
rs.Close(); WebResponse wresp = null;
try
{
wresp = wr.GetResponse(); Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
responseStr = reader2.ReadToEnd(); reader2.Close();
stream2.Close();
reader2.Dispose();
stream2.Dispose();
}
catch
{
throw;
}
finally
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
wr.Abort();
wr = null; }
return responseStr;
}
catch
{
//MainForm.Instance.Console("Ruokuai:" + e.Message);
return "";
}
}
Http请求基本方法的更多相关文章
- SpringMVC下Ajax请求的方法,@Responsebody如果返回的是布尔值,ajax不会接到任何回传数据
SpringMVC框架下,如果用ajax向后台请求得方法如果使用@Responsebody返回布尔值的话,ajax得不到任何的回传数据. 但是如果返回String类型,就是正常的. 测试了下代码写得没 ...
- php之curl实现http与https请求的方法
原文地址:http://m.jb51.net/show/56492 这篇文章主要介绍了php之curl实现http与https请求的方法,分别讲述了PHP访问http网页与访问https网页的实例 ...
- thinkphp 定位查询 Model:last您所请求的方法不存在!
thinkphp 定位查询 Model:last您所请求的方法不存在! 用thinkphp3.1做项目的时候为了获取记录表中最后一个id用到了last()方法,出现了这个错误:Model:last ...
- Nginx反向代理、CORS、JSONP等跨域请求解决方法总结
由于 Javascript 同源策略的存在使得一个源中加载来自其它源中资源的行为受到了限制.即会出现跨域请求禁止. 通俗一点说就是如果存在协议.域名.端口或者子域名不同服务端,或一者为IP地址,一者为 ...
- webServices 使用GET请求接口方法
webServices 若要使用GET请求接口方法在Web.config 下添加这段 <webServices> <protocols> <add ...
- legend2---开发日志10(ajax请求的方法是否同样会执行base控制器里面的方法)
legend2---开发日志10(ajax请求的方法是否同样会执行base控制器里面的方法) 一.总结 一句话总结:会执行的,所以写base控制器里面的方法要注意,base控制器里面的方法要以查数据为 ...
- 发送http请求的方法
在http/1.1 协议中,定义了8种发送http请求的方法 get post options head put delete trace connect patch. 根据http协议的设计初衷,不 ...
- 使用SpringAOP获取一次请求流经方法的调用次数和调用耗时
引语 作为工程师,不能仅仅满足于实现了现有的功能逻辑,还必须深入认识系统.一次请求,流经了哪些方法,执行了多少次DB操作,访问了多少次文件操作,调用多少次API操作,总共有多少次IO操作,多少CPU操 ...
- 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)
Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...
随机推荐
- python内置函数之attr【反射】
#Auther Bob#--*--conding:utf-8 --*-- #我们来循序渐进的学习反射 import s1 #阶段1# def run():# url = input("请输入 ...
- C++的MFC 与 HTML 双向通讯
C++中嵌入ie浏览器总结(1) - ie边框 及上下文菜单 最近项目中用html 来做界面,也就折腾了一下在wxwidget中嵌入浏览器的若干细节工作,mfc也基本是类似的,由于wxwidget中已 ...
- Django之XSS攻击
一.什么是XSS攻击 xss攻击:----->web注入 xss跨站脚本攻击(Cross site script,简称xss)是一种“HTML注入”,由于攻击的脚本多数时候是跨域的,所以称 ...
- PAT 1065 单身狗(25)(STL-map+思路+测试点分析)
1065 单身狗(25 分) "单身狗"是中文对于单身人士的一种爱称.本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱. 输入格式: 输入第一行给出一个正整数 N(≤ ...
- SSH登录到远程linux机器并执行命令
一. 1.JSch是Java Secure Channel的缩写.JSch是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成 ...
- 解压查看二进制rpm包的方法
详细参考: man cpio 具体方法: rpm2cpio qt5-qtbase-5.6.0-13.fc21.x86_64.rpm | cpio -dium 执行后可在当前目录查看 安装目录 etc ...
- Java数据结构和算法(三)顺序存储的树结构
Java数据结构和算法(三)顺序存储的树结构 二叉树也可以用数组存储,可以和完全二叉树的节点一一对应. 一.树的遍历 // 二叉树保存在数组中 int[] data; public void preO ...
- 彻底关闭win10的自动更新,一定要坚持看到最后一页
https://jingyan.baidu.com/article/9faa7231e7b78b473c28cbb6.html 是否好使我还在测试,不好使的话,再跟新 2018-05-20 今天电脑又 ...
- fms +fme 视频直播
1.安装fms 按默认安装即可 2.安装fme 安装完成后启动fme FMS URL是发布到fms的地址默认就可以, 然后点击 Connect 连接成功后左下角会出现connected的提示, 然后点 ...
- 打开jsp页面时,显示空白页。
打开jsp页面时,显示空白页. #foreach($e in $listPlanItem) #set($listPlanDetail=$!e.get(2)) < ...