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, 0, 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 = 30000;
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 = 0; i < pathList.Count; i++)
{
int pos = pathList[i].LastIndexOf("\\");
string fileName = pathList[i].Substring(pos + 1); //取文件名
//请求头部信息
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, 0, bArr.Length);
fs.Close();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
}
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close();
//发送请求并获取相应回应数据
return request.GetResponse() as HttpWebResponse;
}
}
}