using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq; namespace Share
{
public class HttpHelp
{
/// <summary>
/// url为请求的网址,param参数为需要查询的条件(服务端接收的参数,没有则为null)
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Get(string url, Dictionary<string, string> param)
{
if (param != null) //有参数的情况下,拼接url
{
url = url + "?";
url = param.Aggregate(url, (current, item) => current + item.Key + "=" + item.Value + "&");
url = url.Substring(, url.Length - );
}
#region 写日记 LogHelp.WriteLog(url);
#endregion
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求
request.Method = "GET"; //请求方法为GET
HttpWebResponse res; //定义返回的response
try
{
res = (HttpWebResponse)request.GetResponse(); //此处发送了请求并获得响应
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //响应转化为String字符串
return content;
}
//url为请求的网址,param为需要传递的参数
//返回服务端的额响应
/// <summary>
/// url为请求的网址,param为需要传递的参数
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Post(string url, Dictionary<String, String> param)
{
#region 写日记
string parameterSt = "";
if (param.Count != ) //将参数添加到json对象中
{
foreach (var item in param)
{
parameterSt += "&" + item.Key + "=" + item.Value;
}
}
LogHelp.WriteLog(url + parameterSt);
#endregion HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //创建请求
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
//request.AllowReadStreamBuffering = true;
request.MaximumResponseHeadersLength = ;
request.Method = "POST"; //请求方式为post
request.AllowAutoRedirect = true;
request.MaximumResponseHeadersLength = ;
request.ContentType = "application/json";
JObject json = new JObject();
if (param.Count != ) //将参数添加到json对象中
{
foreach (var item in param)
{
json.Add(item.Key, item.Value);
}
}
string jsonstring = json.ToString();//获得参数的json字符串
byte[] jsonbyte = Encoding.UTF8.GetBytes(jsonstring);
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, , jsonbyte.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse res;
try
{
res = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //获得响应字符串
return content;
} //url为请求的网址,param为需要传递的参数
//返回服务端的额响应
/// <summary>
/// url为请求的网址,param为需要传递的参数
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Post(string url, string jsonstring = "")
{
#region 写日记 LogHelp.WriteLog(url + jsonstring);
#endregion HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //创建请求
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
//request.AllowReadStreamBuffering = true;
request.MaximumResponseHeadersLength = ;
request.Method = "POST"; //请求方式为post
request.AllowAutoRedirect = true;
request.MaximumResponseHeadersLength = ;
request.ContentType = "application/json"; byte[] jsonbyte = Encoding.UTF8.GetBytes(jsonstring);
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, , jsonbyte.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse res;
try
{
res = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //获得响应字符串
return content;
} /// <summary>
/// HttpUploadFile 上传文件 HttpUploadFile("http://localhost/Test", new string[] { @"E:\Index.htm", @"E:\test.rar" }, data));
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, Dictionary<string, string> param = null)
{
Encoding encoding = Encoding.UTF8;
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); //1.HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials; using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (param != null)
{
foreach (string key in param.Keys)
{
stream.Write(boundarybytes, , boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, param[key]);
byte[] formitembytes = encoding.GetBytes(formitem);
stream.Write(formitembytes, , formitembytes.Length);
}
} //1.2 file
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] buffer = new byte[];
int bytesRead = ;
for (int i = ; i < files.Length; i++)
{
stream.Write(boundarybytes, , boundarybytes.Length);
string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
byte[] headerbytes = encoding.GetBytes(header);
stream.Write(headerbytes, , headerbytes.Length);
using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, , buffer.Length)) != )
{
stream.Write(buffer, , bytesRead);
}
}
} //1.3 form end
stream.Write(endbytes, , endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
} } /// <summary>
/// 文件下载
/// </summary>
/// <param name="url">抓取url</param>
/// <param name="filePath">保存文件名</param>
/// <param name="oldurl">来源路径</param>
/// <returns></returns>
public static void HttpDownloadFile(string url, string filePath)
{
try
{
HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(url); HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
Stream st = myrp.GetResponseStream();
Stream so = new FileStream(filePath, FileMode.Create);
long totalDownloadedByte = ;
byte[] by = new byte[];
int osize = st.Read(by, , (int)by.Length);
while (osize > )
{
totalDownloadedByte = osize + totalDownloadedByte;
so.Write(by, , osize);
osize = st.Read(by, , (int)by.Length);
}
so.Close();
st.Close();
} catch (Exception ex)
{
LogHelp.WriteLog(ex.Message + ex.StackTrace);
}
}
}
}

用法:

  public FindCabinetListRpModel FindCabinetList(FindCabinetListRt rt)
{
GetToken(rt);
ConvertHelp.NoProperties.Clear();
string parameterSt = ConvertHelp.GetProperties(rt);
Uri address = new Uri(_baseAddress + "/pickup/findCabinetList?" + parameterSt);
string rpJson = HttpHelp.Post(address.ToString()); try
{
//调用接口
var rpModel = JSONHelp.parse<FindCabinetListRpModel>(rpJson);
return rpModel;
}
catch (Exception ex)
{
throw ex;
}
}
05-11 23:02