HttpRequest 工具
1.根据 url 和 encoding 获取当前url页面的 html 源代码
public static string GetHtml(string url, Encoding encoding)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader reader = null;
try
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < * )
{
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding);
else
reader = new StreamReader(response.GetResponseStream(), encoding);
string html = reader.ReadToEnd(); return html;
}
}
catch (Exception ex)
{
}
finally
{ if (response != null)
{
response.Close();
response = null;
}
if (reader != null)
reader.Close(); if (request != null)
request = null;
}
return string.Empty;
}
2.获取URL访问的HTML内容
public static string GetWebContent(string Url)
{
string strResult = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Timeout = ;
request.Headers.Set("Pragma", "no-cache"); HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream(); Encoding encoding = Encoding.GetEncoding("utf-8");
StreamReader streamReader = new StreamReader(streamReceive, encoding);
strResult = streamReader.ReadToEnd();
}
catch
{ } return strResult;
}
3.根据网站url获取流
public static Stream GetWebUrlStream(string Url)
{
Stream stream = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
}
return stream;
}
4.根据发送数据获取url 流对象
public static Stream GetWebUrlStream(string Url, string body)
{
Stream stream = null;
Encoding code = Encoding.GetEncoding("utf-8");
byte[] bytesRequestData = code.GetBytes(body);
try
{
//设置HttpWebRequest基本信息
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Timeout = ;
request.Method = "post";
request.ContentType = "application/octet-stream";
//填充POST数据
request.ContentLength = bytesRequestData.Length; Stream reqStream = request.GetRequestStream();
reqStream.Write(bytesRequestData, , bytesRequestData.Length);
HttpWebResponse wr = (HttpWebResponse)request.GetResponse();
if (wr.StatusCode == HttpStatusCode.OK)
{
//在这里对接收到的页面内容进行处理
stream = wr.GetResponseStream();
}
}
catch { }
return stream;
}
5.根据post 数据填充url 获取html对象
public static string PostHtml(string Url, string body)
{
Encoding code = Encoding.GetEncoding("utf-8");
byte[] bytesRequestData = code.GetBytes(body);
string strResult = "";
try
{
//设置HttpWebRequest基本信息
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Timeout = ;
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; //填充POST数据
request.ContentLength = bytesRequestData.Length; using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bytesRequestData, , bytesRequestData.Length);
}
using (WebResponse wr = request.GetResponse())
{
//在这里对接收到的页面内容进行处理
Stream myStream = wr.GetResponseStream();
//获取数据必须用UTF8格式
StreamReader sr = new StreamReader(myStream, code);
strResult = sr.ReadToEnd();
}
}
catch { }
return strResult;
}
6.将本地文件上传到指定的服务器(HttpWebRequest方法)
public static string PostUpData(string address, string fileNamePath, string saveName, string dataName)
{
string returnValue = "";
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);//时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
//请求头部信息
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", dataName, saveName);
sb.Append("\r\n");
sb.Append("Content-Type: application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
//根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(address);
httpReq.Method = "POST";
//对发送的数据不使用缓存
httpReq.AllowWriteStreamBuffering = false;
//设置获得响应的超时时间(300秒)
httpReq.Timeout = ;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
long fileLength = fs.Length;
httpReq.ContentLength = length;
try
{
Stream postStream = httpReq.GetRequestStream();
//发送请求头部消息
postStream.Write(postHeaderBytes, , postHeaderBytes.Length); //每次上传4k
byte[] buffer = new Byte[checked((uint)Math.Min(, (int)fs.Length))];
fs.Seek(, SeekOrigin.Begin);
int bytesRead = ;
while ((bytesRead = fs.Read(buffer, , buffer.Length)) != )
postStream.Write(buffer, , bytesRead);
//添加尾部的时间戳
postStream.Write(boundaryBytes, , boundaryBytes.Length);
postStream.Close();
//获取服务器端的响应
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);
//读取服务器端返回的消息
returnValue = sr.ReadToEnd();
s.Close();
sr.Close();
}
catch
{ }
finally
{
fs.Close();
}
return returnValue;
}
7.将网址图片上传到指定的服务器(HttpWebRequest方法)
public static string PostUpDataUrlImg(string address, string fileNamePath, string saveName, string dataName)
{
string returnValue = "";
// 要上传的文件
System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;
Image original_image = Image.FromStream(GetWebUrlStream(fileNamePath));
MemoryStream ms = new MemoryStream();
original_image.Save(ms, format);
original_image.Clone();
//时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
//请求头部信息
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", dataName, saveName);
sb.Append("\r\n");
sb.Append("Content-Type: application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
//根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(address);
httpReq.Method = "POST";
//对发送的数据不使用缓存
httpReq.AllowWriteStreamBuffering = false;
//设置获得响应的超时时间(30秒)
httpReq.Timeout = ;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = ms.Length + postHeaderBytes.Length + boundaryBytes.Length;
long fileLength = ms.Length;
httpReq.ContentLength = length;
try
{
Stream postStream = httpReq.GetRequestStream();
//发送请求头部消息
postStream.Write(postHeaderBytes, , postHeaderBytes.Length); //每次上传4k
byte[] buffer = new Byte[checked((uint)Math.Min(, (int)ms.Length))];
ms.Seek(, SeekOrigin.Begin);
int bytesRead = ;
while ((bytesRead = ms.Read(buffer, , buffer.Length)) != )
postStream.Write(buffer, , bytesRead);
//添加尾部的时间戳
postStream.Write(boundaryBytes, , boundaryBytes.Length);
postStream.Close();
//获取服务器端的响应
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);
//读取服务器端返回的消息
returnValue = sr.ReadToEnd();
s.Close();
sr.Close();
}
catch
{ }
finally
{
ms.Close();
}
return returnValue;
}
8.将网络地址文件上传到指定的服务器
public static string PostHttpUpData(string address, string fileNamehttp, string saveName, string dataName)
{
string returnValue = "";
WebClient wc = new WebClient();
//网址文件下载
byte[] downData = wc.DownloadData(fileNamehttp);
wc.Dispose();
//时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
//请求头部信息
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", dataName, saveName);
sb.Append("\r\n");
sb.Append("Content-Type: application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
//根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(address);
httpReq.Method = "POST";
//对发送的数据不使用缓存
httpReq.AllowWriteStreamBuffering = false;
//设置获得响应的超时时间(300秒)
httpReq.Timeout = ;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = downData.Length + postHeaderBytes.Length + boundaryBytes.Length;
httpReq.ContentLength = length;
try
{
Stream postStream = httpReq.GetRequestStream();
//发送请求头部消息
postStream.Write(postHeaderBytes, , postHeaderBytes.Length); //发送内容消息
postStream.Write(downData, , downData.Length); //添加尾部的时间戳
postStream.Write(boundaryBytes, , boundaryBytes.Length); postStream.Close();
//获取服务器端的响应
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);
//读取服务器端返回的消息
returnValue = sr.ReadToEnd();
s.Close();
sr.Close();
}
catch { }
return returnValue;
}
9.将网址图片上传到指定的服务器(HttpWebRequest方法)
public static string PostUpDataUrlImg(string address, string fileNamePath, string saveName, string dataName, string body)
{
string returnValue = "";
Stream stream = GetWebUrlStream(fileNamePath, body);
List<byte> bytes = new List<byte>();
int temp = stream.ReadByte();
while (temp != -)
{
bytes.Add((byte)temp);
temp = stream.ReadByte();
}
byte[] WebUrlStream = bytes.ToArray();//时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
//请求头部信息
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", dataName, saveName);
sb.Append("\r\n");
sb.Append("Content-Type: application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
//根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(address);
httpReq.Method = "POST";
//对发送的数据不使用缓存
httpReq.AllowWriteStreamBuffering = false;
//设置获得响应的超时时间(30秒)
httpReq.Timeout = ;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = WebUrlStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
long fileLength = WebUrlStream.Length;
httpReq.ContentLength = length;
try
{
Stream postStream = httpReq.GetRequestStream();
//发送请求头部消息
postStream.Write(postHeaderBytes, , postHeaderBytes.Length);
postStream.Write(WebUrlStream, , WebUrlStream.Length);
//添加尾部的时间戳
postStream.Write(boundaryBytes, , boundaryBytes.Length);
postStream.Close();
//获取服务器端的响应
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);
//读取服务器端返回的消息
returnValue = sr.ReadToEnd();
s.Close();
sr.Close();
}
catch
{ }return returnValue;
}
HttpRequest 工具的更多相关文章
- slim
Slim 是一个非常优雅的 PHP 微框架,非常适合做API,支持多种http请求方式,比如get,post,delete,put等 安装使用Composer composer require sli ...
- 微信小程序:java后台获取openId
一.功能描述 openId是某个微信账户对应某个小程序或者公众号的唯一标识,但openId必须经过后台解密才能获取(之前实现过前台解密,可是由于微信小程序的种种限制,前台解密无法在小程序发布后使用) ...
- java开发微信公众号支付(JSAPI)
https://www.cnblogs.com/gopark/p/9394951.html,这篇文章写的已经很详细了. 下面写一下自己的思路: 1.首先下载demo,地址:https://pay.we ...
- Java请求Http
一.工具类,直接粘贴调用即可 package cn.com.service.httpReq; import java.io.BufferedReader;import java.io.IOExcept ...
- 树莓派学习笔记——Restful服务 采用slim php apache
0.前言 前些时间沉迷于Restful,采用PHP+Slim+MySQL实现了一些简单的API函数.但是这些工作都是在windows中实现(采用wamp server集成安装包),但是转到li ...
- java工具类
1.HttpUtilsHttp网络工具类,主要包括httpGet.httpPost以及http参数相关方法,以httpGet为例:static HttpResponse httpGet(HttpReq ...
- WPF开发查询加班小工具
先说一下,我们公司是六点下班,超过7点开始算加班,但是加班的时间是从六点开始计算,以0.5个小时为计数,就是你到了六点半,不算加班半小时,但是加班到七点半,就是加班了一个半小时. 一.打卡记录 首先, ...
- java http工具类和HttpUrlConnection上传文件分析
利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...
- Android高手速成--第二部分 工具库
主要包括那些不错的开发库,包括依赖注入框架.图片缓存.网络相关.数据库ORM建模.Android公共库.Android 高版本向低版本兼容.多媒体相关及其他. 一.依赖注入DI 通过依赖注入减少Vie ...
随机推荐
- pywebview gui='cef' 生成app报错—— 中断点 已到达中断点
pywebview是一个轻量级跨平台包装器,允许在其自己的本机GUI窗口中显示HTML内容.它提供了桌面应用程序中Web技术的强大功能,隐藏了GUI基于浏览器的事实.这个玩意儿好啊,可以直接让我们做的 ...
- Luogu P2484 [SDOI2011]打地鼠(模拟+前缀和)
P2484 [SDOI2011]打地鼠 题意 题目描述 打地鼠是这样的一个游戏:地面上有一些地鼠洞,地鼠们会不时从洞里探出头来很短时间后又缩回洞中.玩家的目标是在地鼠伸出头时,用锤子砸其头部,砸到的地 ...
- 制作windows10系统启动U盘,从零开始。
1.打开百度,搜索windows下载,选个这个点击进去. 2.会看到下图,然后点击立即下载工具按钮. 3.接下来由于网络的原因,可能需要漫长的等待.会下载一个MediaCreationTool1903 ...
- 使用log4j实现日志API
添加SLF4J依赖,用于提供日志API, 使用log4j作为实现 1.pom.xml添加SLF4J依赖 <!-- SLF4J --> <dependency> <grou ...
- odoo 下 get_object_reference 函数
get_object_reference是 ir.model.data 模块中下的一个函数 该函数通过调用ir.model.data 模块中另外一个函数 xmlid_lookup 返回结果 def g ...
- 菜鸟nginx源码剖析数据结构篇(十) 自旋锁ngx_spinlock[转]
菜鸟nginx源码剖析数据结构篇(十) 自旋锁ngx_spinlock Author:Echo Chen(陈斌) Email:chenb19870707@gmail.com Blog:Blog.csd ...
- Hibernate 查询语言
查询语言 Hibernate 查询语言(HQL)是一种面向对象的查询语言,类似于 SQL,但不是去对表和列进行操作,而是面向对象和它们的属性. HQL 查询被 Hibernate 翻译为传统的 SQL ...
- Netty ByteBuf泄露定位修改。
1. ByteBuf 2. 问题描述 日志记录中报堆外内存溢出. 3. 问题定位及修改 Netty提供了ByteBuf泄露的检测机制. JVM启动参数中添加: -Dio.netty.leakDetec ...
- 服务器IP配置功能实现小结
1. 服务器网卡配置文件 /etc/sysconfig/network/ifcfg-***(eth0) linux-f1s9:/etc/sysconfig/network # cat ifcfg-et ...
- python学习笔记4.1_检测和过滤异常值
1.查看数据分布data.describe() 2.找出某列中符合筛选条件的值 3.找出符合筛选条件的行 4.用np.sign(data)*3设置绝对值的标准 data[np.abs(data)> ...