using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text; namespace ZhuoHuiSchoolRoom.ZhuoHuiClass
{
class HttpWebResponseUtility
{
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; /// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
} /// <summary>
/// 创建POST方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="str">json字符串</param>
/// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
/// <returns></returns>
public static HttpWebResponse CreatePostHttpResponse(string url, string str, Encoding requestEncoding)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST";
request.ContentType = "application/json;charset=utf-8";
request.UserAgent = DefaultUserAgent; byte[] data = requestEncoding.GetBytes(str.ToString()); //将json转为二进制流
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, , data.Length);
} return request.GetResponse() as HttpWebResponse;
} /// <summary>
/// 创建DELETE方式的HTTP请求
/// </summary>
/// <param name="url">请求地址</param>
/// <returns></returns>
public static HttpWebResponse CreateDeleteHttpResponse(string url)
{
HttpWebRequest request = null;
string urlPath = url;
int millisecond = ;
request = (HttpWebRequest)WebRequest.Create(urlPath);
//request.Proxy = null;//关闭代理(重要)
request.Timeout = millisecond;
request.Method = "DELETE";
//request.Accept = "application/json";
//request.ContentType = "application/json";
request.ServicePoint.Expect100Continue = false;
return request.GetResponse() as HttpWebResponse;
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
} /// <summary>
/// HttpPost上传多个文件
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="pathList">路径集合</param>
/// <returns></returns>
public static HttpWebResponse HttpUploadFile(string url, List<string> pathList)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = "----" + DateTime.Now.Ticks.ToString("x"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); Stream postStream = request.GetRequestStream();
for (int i = ; i < pathList.Count; i++)
{
int pos = pathList[i].LastIndexOf("\\");
string fileName = pathList[i].Substring(pos + ); //取文件名
//请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); FileStream fs = new FileStream(pathList[i], FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, , bArr.Length);
fs.Close(); postStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, , postHeaderBytes.Length);
postStream.Write(bArr, , bArr.Length); }
postStream.Write(endBoundaryBytes, , endBoundaryBytes.Length);
postStream.Close(); //发送请求并获取相应回应数据
return request.GetResponse() as HttpWebResponse;
}
}
}

最新文章

  1. Github上有趣的资料 | JS
  2. Windows Azure Cloud Service (1) 用户手册
  3. CMD命令简单使用
  4. System.BadImageFormatException : 未能加载文件或程序集“Medici.PaymentRecover, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项。试图加载格式不正确的程序。
  5. Yii2 使用八 使用scenarios
  6. Visual Studio 2013下JSON可视化工具
  7. php函数描述及例子
  8. CUBRID学习笔记 42 Hierarchical QuerySQL层级查询
  9. line-hight-(行高)解析
  10. BZOJ 1034: [ZJOI2008]泡泡堂BNB( 贪心 )
  11. centos手动配置IP和DNS
  12. Java基础中一些容易被忽视的语法小细节总结
  13. bash编程语法自我总结
  14. Java之判断大整数是否为平方数
  15. express 连接数据库
  16. linux audit审计(2)--audit启动
  17. sql-leetcode Consecutive Numbers
  18. python全栈开发day98-DRF
  19. javascript-序列化,时间,eval,转义
  20. HTML一些标签注意事项

热门文章

  1. hdu 1708 Fibonacci String
  2. js实现点击隐藏图片
  3. Wunder Fund Round 2016 (Div. 1 + Div. 2 combined)
  4. 我来教你用AWS IoT.Part1--配置和接入
  5. CSS滤镜 :灰色 ,方便站点哀悼
  6. 带你认识“货真价实”的P2P网贷风控
  7. BZOJ 4236 &quot;JOIOJI&quot;(前缀和+map+pair)
  8. 【hdu 1112】The Proper Key
  9. The Preliminary Contest for ICPC Asia Nanjing 2019ICPC南京网络赛
  10. HashMap深入理解