?/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述:Http請(qǐng)求工具類(lèi)
*│ Get :像數(shù)據(jù)庫(kù)的select,只是用來(lái)查詢(xún)一下數(shù)據(jù),不會(huì)修改、增加數(shù)據(jù),不會(huì)影響資源的內(nèi)容。
*│ Post :像數(shù)據(jù)庫(kù)的insert操作一樣,會(huì)創(chuàng)建新的內(nèi)容。幾乎目前所有的提交操作都是用POST請(qǐng)求的。
*│ Put :像數(shù)據(jù)庫(kù)的update操作一樣,用來(lái)修改數(shù)據(jù)的內(nèi)容,但是不會(huì)增加數(shù)據(jù)的種類(lèi)等。
*│ Delete :像數(shù)據(jù)庫(kù)的delete操作
*│ 作 者:執(zhí)筆小白
*│ 版 本:2.1
*│ 創(chuàng)建時(shí)間:2021-10-20 15:40:56~2023-03-25 22:42:56
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空間: WebserviceWcfWebAPITestTool.ASPNetCoreWebAPI_Test
*│ 類(lèi) 名:WebAPITestForm
*└──────────────────────────────────────────────────────────────┘
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using static System.Net.WebRequestMethods;
namespace CommonTools
{
// 請(qǐng)求工具類(lèi)
// HttpWebRequest(WebRequest.Create):.NET.Framework的請(qǐng)求/響應(yīng)模型的抽象基類(lèi),用于訪(fǎng)問(wèn)Internet數(shù)據(jù)。
// HttpWebResponse:對(duì)http協(xié)議進(jìn)行了完整的封裝( Header, Content, Cookie),與HttpWebRequest結(jié)合使用。
public class RequestCom
{
#region WebAPI
/// <summary>
/// Get方法
/// </summary>
/// 例如:http://localhost:30202/api/ValuesTest/Sum?num1=1&num2=3
/// <param name="postData">后綴(?num1=1&num2=3)</param>
/// <param name="Url">url(http://localhost:30202/api/ValuesTest/Sum)</param>
/// <returns></returns>
public static string GetInfo(string postData, string Url)
{
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.ContentLength = byteArray.Length;
webRequest.Accept = "application/json, text/javascript, */*";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
return sr.ReadToEnd(); // 返回的數(shù)據(jù)
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Post請(qǐng)求
/// </summary>
/// <param name="url">URL</param>
/// <param name="body">application/json</param>
/// <returns></returns>
public static string HttpPost(string url, string body)
{
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(body);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.ContentLength = byteArray.Length;
webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);
webRequest.Accept = "application/json, text/javascript, */*";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Put請(qǐng)求-必有body
/// </summary>
/// <param name="url">URL</param>
/// <param name="body">application/json</param>
/// <returns></returns>
public static string HttpPut(string url, string body)
{
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(body);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "PUT";
webRequest.ContentType = "application/json";
webRequest.ContentLength = byteArray.Length;
webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);
webRequest.Accept = "application/json, text/javascript, */*";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Delete請(qǐng)求-必有body
/// </summary>
/// <param name="url">URL</param>
/// <param name="body">application/json</param>
/// <returns></returns>
public static string HttpDelete(string url, string body)
{
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(body);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "DELETE";
webRequest.ContentType = "application/json";
webRequest.ContentLength = byteArray.Length;
webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);
webRequest.Accept = "application/json, text/javascript, */*";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
#region WebService
/// <summary>
/// Set
/// </summary>
/// <summary>
/// Post方法-拼接Body組方式:ReqBody參數(shù)組(Key,Value)
/// </summary>
/// <param name="url">webService的URL</param>
/// <param name="method">調(diào)用的方法</param>
/// <param name="reqBodys">參數(shù)組合</param>
/// <returns></returns>
public static string WebServiceHttpPost(string URL, string Method, List<ReqBody> ReqBodys, Encoding requestCoding, int timeout = 30000)
{
string param = string.Empty;
switch (ReqBodys.Count)
{
case 0:
break;
case 1:
param = HttpUtility.UrlEncode(ReqBodys[0].Key) + "=" + HttpUtility.UrlEncode(ReqBodys[0].Value);
break;
default:
param = HttpUtility.UrlEncode(ReqBodys[0].Key) + "=" + HttpUtility.UrlEncode(ReqBodys[0].Value);
for (int i = 1; i < ReqBodys.Count; i++)
{
param += "&" + HttpUtility.UrlEncode(ReqBodys[i].Key) + "=" + HttpUtility.UrlEncode(ReqBodys[i].Value);
}
break;
}
//byte[] byteArray = Encoding.UTF8.GetBytes(param);
byte[] byteArray = requestCoding.GetBytes(param);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(URL + "/" + Method);
webRequest.Method = "POST";
webRequest.Timeout = timeout;
// webRequest.UserAgent = "DefaultUserAgent";
webRequest.ContentType = "application/x-www-form-urlencoded"; // 瀏覽器默認(rèn)的編碼格式
webRequest.ContentLength = byteArray.Length;
webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length); //把參數(shù)數(shù)據(jù)寫(xiě)入請(qǐng)求數(shù)據(jù)的Stream對(duì)象
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); //獲得響應(yīng)
#region 只返回Response的Xml報(bào)文(Body內(nèi)容)
using (XmlTextReader reader = new XmlTextReader(webResponse.GetResponseStream())) //獲取響應(yīng)流
{
reader.MoveToContent();
return reader.ReadInnerXml();
}
#endregion 只返回Response的Xml報(bào)文(Body內(nèi)容)
#region 返回所有Xml報(bào)文
//using(StreamReader sr = new StreamReader(webResponse.GetResponseStream(), requestCoding))
//{
// return sr.ReadToEnd();
//}
#endregion 返回所有Xml報(bào)文
}
/// <summary>
/// Post方法-拼接xml方式
/// 下面有示例"Post方法-拼接xml方式示例"
/// </summary>
/// <param name="url">webService的URL</param>
/// <param name="soapAction">soap方法,可為null</param>
/// <param name="soap_Namespace">soap的命名空間</param>
/// <param name="soap_EnvelopeXml">soap:Envelope的信息</param>
/// <param name="soap_HeaderXml">soap:Header的信息</param>
/// <param name="soap_BodyXml">soap:Body的信息</param>
/// <param name="requestCoding">編碼格式</param>
/// <param name="timeout">超時(shí)</param>
/// <returns></returns>
public static string WebServiceHttpPost(string url, string soapAction, string soap_Namespace, string soap_EnvelopeXml, string soap_HeaderXml, string soap_BodyXml, Encoding requestCoding, int timeout = 30000)
{
// 確認(rèn)編碼
string requestCodingStr = "UTF-8";
switch (requestCoding)
{
case UTF8Encoding:
requestCodingStr = "UTF-8";
break;
case UTF32Encoding:
requestCodingStr = "UTF-32";
break;
case ASCIIEncoding:
requestCodingStr = "ASCII";
break;
default:
break;
}
string requestXml = GetPostStr(requestCodingStr, soap_Namespace, soap_EnvelopeXml, soap_HeaderXml, soap_BodyXml); // 拼接xml
//byte[] byteArray = Encoding.UTF8.GetBytes(requestXml);
byte[] byteArray = requestCoding.GetBytes(requestXml);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = timeout;
//httpWebRequest.ContentType = "application/x-www-form-urlencoded"; // 瀏覽器默認(rèn)的編碼格式
httpWebRequest.ContentType = $"text/xml;charset={requestCodingStr}"; // xml編碼格式
if (soapAction != null)
{
httpWebRequest.Headers.Add("SOAPAction", soapAction); // SOAP方法,有的需要設(shè)置(SOAP 1.1不一定需要;SOAP1.2不需要設(shè)置)
}
//httpWebRequest.Headers.Add("Accept-Language", "zh-cn,en-US,en;q=0.5");
//httpWebRequest.Headers.Add("Cache-Control", "no-cache");
//httpWebRequest.UserAgent = "DefaultUserAgent";
httpWebRequest.ContentLength = byteArray.Length;
httpWebRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length); // 把參數(shù)數(shù)據(jù)寫(xiě)入請(qǐng)求數(shù)據(jù)的Stream對(duì)象
// 接收返回信息
HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
#region 只返回Response的Xml報(bào)文(Body內(nèi)容)
using (XmlTextReader reader = new XmlTextReader(webResponse.GetResponseStream())) //獲取響應(yīng)流
{
reader.MoveToContent();
return reader.ReadInnerXml();
}
#endregion 只返回Response的Xml報(bào)文(Body內(nèi)容)
#region 返回所有Xml報(bào)文
//using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), requestCoding)) // 返回Xml格式的字符串
//{
// return sr.ReadToEnd();
//}
#endregion 返回所有Xml報(bào)文
}
// Post方法-拼接xml方式示例
//private void button1_Click(object sender, EventArgs e)
//{
// string soap_Namespace = "soap";
//string soap_EnvelopeXml = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"";
//string soap_HeaderXml = string.Empty;
//string soap_BodyXml = " <HelloWorld xmlns=\"http://tempuri.org/\" />";
//Encoding requestCoding = Encoding.UTF8;
//string result = RequestCom.WebServiceHttpPost(url, soap_Namespace, soap_EnvelopeXml, soap_HeaderXml, soap_BodyXml, requestCoding);
//textBox5.Text = result;
//}
/// <summary>
/// 拼接HttpWebResponse的RequestStream
/// </summary>
/// <param name="requestCodingStr">編碼格式</param>
/// <param name="soap_Namespace">soap的命名空間</param>
/// <param name="soap_EnvelopeXml">soap:Envelope的信息</param>
/// <param name="soap_HeaderXml">soap:Header的信息</param>
/// <param name="soap_BodyXml">soap:Body的信息</param>
private static string GetPostStr(string requestCodingStr, string soap_Namespace, string soap_EnvelopeXml, string soap_HeaderXml, string soap_BodyXml)
{
// 拼接參數(shù)
string postStr = string.Empty;
postStr = $"<?xml version=\"1.0\" encoding=\"{requestCodingStr}\"?> ";
// soap:Envelope的信息
//<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
//<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
//<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tip=""http://www.digiwin.com.cn/tiptop/TIPTOPServiceGateWay"">
postStr += $"<{soap_Namespace}:Envelope " + soap_EnvelopeXml + ">";
// soap:Header的信息
//<soap:Header></soap:Header>
//<soap12:Header></soap12:Header>
//<soapenv:Header></soapenv:Header>
postStr += $"<{soap_Namespace}:Header>" + soap_HeaderXml + $"</{soap_Namespace}:Header>";
// soap:Body的信息
//<soap12:Body>
//<HelloWorld xmlns="http://tempuri.org/" />
//</soap12:Body>
postStr += $"<{soap_Namespace}:Body>" + soap_BodyXml + $"</{soap_Namespace}:Body>";
postStr += $"</{soap_Namespace}:Envelope>";
return postStr;
}
#endregion WebService
}
// 參數(shù)
public class ReqBody
{
/// <summary>
/// 參數(shù)名
/// </summary>
public string Key { get; set; }
/// <summary>
/// 參數(shù)值
/// </summary>
public string Value { get; set; }
}
}