代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public static class HttpRequestHelper
{
public delegate int handleAsync(string str);
/// <summary>
/// Http Get Request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string HttpGetRequest(string url)
{
string strGetResponse = string.Empty;
try
{
var getRequest = CreateHttpRequest(url, "GET");
var getResponse = getRequest.GetResponse() as HttpWebResponse;
strGetResponse = GetHttpResponse(getResponse, "GET");
}
catch (Exception ex)
{
strGetResponse = ex.Message;
}
return strGetResponse;
}
/// <summary>
/// Http Get Request Async
/// </summary>
/// <param name="url"></param>
public static async void HttpGetRequestAsync(string url)
{
string strGetResponse = string.Empty;
try
{
var getRequest = CreateHttpRequest(url, "GET");
var getResponse = await getRequest.GetResponseAsync() as HttpWebResponse;
strGetResponse = GetHttpResponse(getResponse, "GET");
}
catch (Exception ex)
{
strGetResponse = ex.Message;
}
Console.WriteLine("reslut:" + strGetResponse);
//return strGetResponse;
}
/// <summary>
/// Http Post Request
/// </summary>
/// <param name="url"></param>
/// <param name="postJsonData"></param>
/// <returns></returns>
public static string HttpPostRequest(string url, string postJsonData)
{
string strPostReponse = string.Empty;
try
{
var postRequest = CreateHttpRequest(url, "POST", postJsonData);
var postResponse = postRequest.GetResponse() as HttpWebResponse;
strPostReponse = GetHttpResponse(postResponse, "POST");
}
catch (Exception ex)
{
strPostReponse = ex.Message;
}
return strPostReponse;
}
/// <summary>
/// Http Post Request Async
/// </summary>
/// <param name="url"></param>
/// <param name="postJsonData"></param>
public static async void HttpPostRequestAsync(string url, string postData, handleAsync ha=null)
{
string strPostReponse = string.Empty;
try
{
var postRequest = CreateHttpRequest(url, "POST", postData);
var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
strPostReponse = GetHttpResponse(postResponse, "POST");
}
catch (Exception ex)
{
strPostReponse = ex.Message;
}
if (strPostReponse != "true")
{
//Console.WriteLine("--> reslut : " + strPostReponse);
//Console.WriteLine(postData);
if(null != ha)
{
ha(strPostReponse);
}
}
}
public static string HttpUploadFile(string url, int timeOut, string fileKeyName, string filePath, Dictionary<string, string> list)
{
string responseContent;
var memStream = new MemoryStream();
var webRequest = (HttpWebRequest)WebRequest.Create(url);
// 边界符
var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");//日期的16进制字符串
// 边界符
var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
// 最后的结束符
var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
// 设置属性
webRequest.Method = "POST";
webRequest.Timeout = timeOut;
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
// 写入文件----------1.--------------
// 获取文件名称路径最后一级,以\/分级,不分级则取全路径为文件名
int start = filePath.LastIndexOf("/");
if(-1 == start)
{
start = filePath.LastIndexOf("\\");
if(-1 == start)
{
start = 0;
}
}
string filename = filePath.Substring(start + 1);
string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=" + filename + "\r\n" + "Content-Type: application/octet-stream\r\n\r\n";
var header = string.Format(filePartHeader, fileKeyName, filePath);
Console.WriteLine(header);
var headerbytes = Encoding.UTF8.GetBytes(header);
memStream.Write(beginBoundary, 0, beginBoundary.Length);
memStream.Write(headerbytes, 0, headerbytes.Length);
// 获取文件流
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var buffer = new byte[1024];
int bytesRead; // =0
// 文件流写入缓冲区
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
// 文件后面要有换行
string stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
// 遍历参数,传输数据的编码集----------- 2 -------------------
foreach (var item in list)
{ //
var dataByte = Encoding.UTF8.GetBytes(string.Format(stringKeyHeader, item.Key, item.Value));
memStream.Write(dataByte, 0, dataByte.Length);
}
// 写入最后的结束边界符------------ 3.-------------------------
memStream.Write(endBoundary, 0, endBoundary.Length);
webRequest.ContentLength = memStream.Length;
var requestStream = webRequest.GetRequestStream();
memStream.Position = 0;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
// 响应 ------------------- 4.-----------------------------------
var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
responseContent = httpStreamReader.ReadToEnd();
}
fileStream.Close();
httpWebResponse.Close();
webRequest.Abort();
return responseContent;
}
private static HttpWebRequest CreateHttpRequest(string url, string requestType, string strJson="")
{
HttpWebRequest request = null;
const string get = "GET";
const string post = "POST";
if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
{
request = CreateGetHttpWebRequest(url);
}
if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
{
request = CreatePostHttpWebRequest(url, strJson);
}
return request;
}
private static HttpWebRequest CreateGetHttpWebRequest(string url)
{
var getRequest = HttpWebRequest.Create(url) as HttpWebRequest;
getRequest.Method = "GET";
getRequest.Timeout = 5000;
getRequest.ContentType = "text/html;charset=UTF-8";
getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return getRequest;
}
//utf8编码格式,以免post请求中中文乱码
private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData)
{
System.Net.ServicePointManager.DefaultConnectionLimit = 50;
byte[] data = Encoding.UTF8.GetBytes(postData);
var postRequest = HttpWebRequest.Create(url) as HttpWebRequest;
postRequest.KeepAlive = false;
postRequest.Timeout = 5000;
postRequest.Method = "POST";
postRequest.ContentType = "application/x-www-form-urlencoded;charset=utf8";
postRequest.UserAgent = initUAString();
postRequest.ContentLength = data.Length;
postRequest.AllowWriteStreamBuffering = false;
//StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII);
// 往请求的流里写数据
using (Stream stream = postRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
//writer.Write(data);
//writer.Flush();
return postRequest;
}
private static string GetHttpResponse(HttpWebResponse response, string requestType)
{
var responseResult = "";
const string post = "POST";
string encoding = "UTF-8";
if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
{
encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8";
}
}
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
{
responseResult = reader.ReadToEnd();
}
return responseResult;
}
private static string GetHttpResponseAsync(HttpWebResponse response, string requestType)
{
var responseResult = "";
const string post = "POST";
string encoding = "UTF-8";
if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
{
encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8";
}
}
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
{
responseResult = reader.ReadToEnd();
}
return responseResult;
}
//dictionary转http get参数
public static string DictoryToGetParam(Dictionary<string, string> dict)
{
string param = "";
foreach(KeyValuePair<string, string> kv in dict)
{
param += kv.Key + '=' + kv.Value + '&';
}
if('&' == param[param.Length - 1])
{
param = param.Substring(0, param.Length - 1);
}
return param;
}
}
}
同步调用
//同步http post
static void testHttp()
{
var postUrl = "http://yoururl";
Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("userID", "100000048");
postData.Add("gradeID", "1");
// 自己实现的http请求
string postStr = HttpRequestHelper.DictoryToGetParam(postData);
var repose = HttpRequestHelper.HttpPostRequest(postUrl, postStr);
Console.WriteLine(repose);
}
异步调用
static void testHttpAsync()
{
var postUrl = "http://yoururl";
Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("userID", "100000048");
postData.Add("gradeID", "1");
string postStr = HttpRequestHelper.DictoryToGetParam(postData);
//类中static回调函数handlePostAsync
HttpRequestHelper.HttpPostRequestAsync(getUrl, postStr, handlePostAsync);
Console.WriteLine("http post async done");
Console.Read();
}
//回调函数
static int handlePostAsync(string str)
{
Console.WriteLine("handle post Async : " + str);
return 0;
}
单文件上传带参数
static void testFileUpload()
{
var postUrl = "http://yoururl";
Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("userID", "100000048");
postData.Add("gradeID", "1");
string returnData = HttpRequestHelper.HttpUploadFile(postUrl, 12000, "qrcode_image", "D://0//huojian.png", postData);
Console.WriteLine(returnData);
Console.Read();
}