示例Post 调用
Post 调用,带Header
string url = "http://baidu.com/api/AddUser";
string postData = $"UserName=Miaoming&Age=26";
Hashtable headht = new Hashtable();
headht.Add("UserTokenStr", "key123456");
string Res = HttpMethods.HttpPost(url, postData, headht);
Post 调用,不带Header
string url = "http://baidu.com/api/AddUser";
string postData = $"UserName=Miaoming&Age=26";
string Res = HttpMethods.HttpPost(url, postData);
示例 Get调用
Get调用,带Header
int ID=123;
string url = "http://baidu.com/api/GetUser?ID=" + ID + "&age=16";
Hashtable headht = new Hashtable();
headht.Add("UserTokenStr", "key123456");
UserInfoMode userInfo = HttpMethods.HttpGet(url,headht);
Get调用,不带Header
int ID=123;
string url = "http://baidu.com/api/GetUser?ID=" + ID + "&age=16";
UserInfoMode userInfo = HttpMethods.HttpGet(url);
HttpWebPost完整帮助类
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Quanxi.Yijiao.Mob.App_Tools
{
public class HttpHelp
{
#region POST
public static string HttpPost(string url, string param = null, Hashtable headht = null)
{
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
if (headht != null)
{
foreach (DictionaryEntry item in headht)
{
request.Headers.Add(item.Key.ToString(), item.Value.ToString());
}
}
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
public static string BuildRequest(string strUrl, Dictionary<string, string> dicPara, string fileName)
{
string contentType = "image/jpeg";
FileStream Pic = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] PicByte = new byte[Pic.Length];
Pic.Read(PicByte, 0, PicByte.Length);
int lengthFile = PicByte.Length;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
request.Method = "POST";
string boundaryValue = DateTime.Now.Ticks.ToString("x");
string boundary = "--" + boundaryValue;
request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
request.KeepAlive = true;
StringBuilder sbHtml = new StringBuilder();
foreach (KeyValuePair<string, string> key in dicPara)
{
sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
}
sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"");
sbHtml.Append(fileName);
sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
string postHeader = sbHtml.ToString();
Encoding code = Encoding.GetEncoding("UTF-8");
byte[] postHeaderBytes = code.GetBytes(postHeader);
byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;
request.ContentLength = length;
Stream requestStream = request.GetRequestStream();
Stream myStream = null;
try
{
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
requestStream.Write(PicByte, 0, lengthFile);
requestStream.Write(boundayBytes, 0, boundayBytes.Length);
HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
myStream = HttpWResp.GetResponseStream();
}
catch (WebException e)
{
return "";
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
}
StreamReader reader = new StreamReader(myStream, code);
StringBuilder responseData = new StringBuilder();
String line;
while ((line = reader.ReadLine()) != null)
{
responseData.Append(line);
}
myStream.Close();
Pic.Close();
return responseData.ToString();
}
#endregion
#region Put
public static string HttpPut(string url, string param = null)
{
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
#endregion
#region Delete
public static string HttpDelete(string url, string param = null)
{
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "Delete";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
return responseStr;
}
#endregion
#region Get
public static string HttpGet(string url, Hashtable headht = null)
{
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "GET";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
WebResponse response = null;
string responseStr = null;
if (headht != null)
{
foreach (DictionaryEntry item in headht)
{
request.Headers.Add(item.Key.ToString(), item.Value.ToString());
}
}
try
{
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
return responseStr;
}
public static string HttpGet(string url, Encoding encodeing, Hashtable headht = null)
{
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "GET";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
WebResponse response = null;
string responseStr = null;
if (headht != null)
{
foreach (DictionaryEntry item in headht)
{
request.Headers.Add(item.Key.ToString(), item.Value.ToString());
}
}
try
{
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), encodeing);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
return responseStr;
}
#endregion
#region Post With Pic
private string HttpPost(string url, IDictionary<object, object> param, string filePath)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string responseStr = null;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in param.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, param[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "pic", filePath, "text/plain");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
responseStr = reader2.ReadToEnd();
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
throw;
}
return responseStr;
}
#endregion
#region Post With Pic
public static string HttpPost(string url, IDictionary<object, object> param, byte[] fileByte)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string responseStr = null;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in param.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, param[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "pic", fileByte, "text/plain");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
rs.Write(fileByte, 0, fileByte.Length);
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
responseStr = reader2.ReadToEnd();
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
throw;
}
return responseStr;
}
#endregion
#region HttpsClient
public static HttpClient CreateHttpClient(string url)
{
HttpClient httpclient;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
httpclient = new HttpClient();
}
else
{
httpclient = new HttpClient();
}
return httpclient;
}
#endregion
}
}
BUF加持异步多线程执行
RequestFactory:封装的异步–开辟新的线程请求
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace Quanxi.Yijiao.Mob.App_Tools
{
public class RequestFactory
{
public static async Task<string> HttpGet(string url, Hashtable headht = null)
{
string result = "";
await Task.Run(() =>
{
try
{
result = HttpHelp.HttpGet(url, headht);
}
catch (Exception e)
{
result = e.Message;
}
});
return result;
}
public static async Task<string> HttpPost(string url, string param = null, Hashtable headht = null)
{
string result = "";
await Task.Run(() =>
{
try
{
result = HttpHelp.HttpPost(url, param, headht);
}
catch (Exception e)
{
result = e.Message;
}
});
return result;
}
}
}
asp.net MVC调用
public async Task<ActionResult> Index()
{
try
{
Console.WriteLine("业务--开始");
string url1 = "http://xxx.xxx.xx/data?act=region_list&pcode=0&level=1";
string url2 = "http://xxx.xxx.xx/data?SiteName=yijiao&PageID=4&LocationID=4";
string url3 = "http://xxx.xxx.xx/data?SiteName=kangyang&num=30";
string addJson ="";
string adJson = "";
string linkJson = "";
await Task.Run(() =>
{
Task<string> tStr1 = RequestFactory.HttpGet(url1);
Task<string> tStr2 = RequestFactory.HttpGet(url2);
Task<string> tStr3 = RequestFactory.HttpGet(url3);
addJson = tStr1.Result;
adJson = tStr2.Result;
linkJson = tStr3.Result;
});
Console.WriteLine("业务-结束-----2");
}
catch (Exception e)
{
throw;
}
ViewBag.result = "666666666666";
return View();
}