公司客户需要一个C# DLL 程序集包装 Rest API 的方法后调用DLL中的方法来使用。
这里找到一个rest Api 的通用方法来使用,有2种使用方式,一个是通过证书一个是通过请求头的 Authorization 授权使用,故对其做了一些修改。
通用类:
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
public enum HttpVerb
{
GET, //method 常用的就这几样,当然你也可以添加其他的 get:获取 post:修改 put:写入 delete:删除
POST,
PUT,
DELETE
}
namespace ClassLibrary1
{
public enum HttpVerbNew
{
GET, //method 常用的就这几样,可以添加其他的 get:获取 post:修改 put:写入 delete:删除
POST,
PUT,
DELETE
}
public class ContentType//根据Postman整理,可以添加
{
public string Text = "text/plain";
public string JSON = "application/json";
public string Javascript = "application/javascript";
public string XML = "application/xml";
public string TextXML = "text/xml";
public string HTML = "text/html";
}
public class RestClient
{
public string EndPoint { get; set; } //请求的url地址
public HttpVerbNew Method { get; set; } //请求的方法
public string ContentType { get; set; } //格式类型
public string PostData { get; set; } //传送的数据
public RestClient()
{
EndPoint = "";
Method = HttpVerbNew.GET;
ContentType = "text/xml";
PostData = "";
}
public RestClient(string endpoint, string contentType)
{
EndPoint = endpoint;
Method = HttpVerbNew.GET;
ContentType = contentType;
PostData = "";
}
public RestClient(string endpoint, HttpVerbNew method, string contentType)
{
EndPoint = endpoint;
Method = method;
ContentType = contentType;
PostData = "";
}
public RestClient(string endpoint, HttpVerbNew method, string contentType, string postData)
{
EndPoint = endpoint;
Method = method;
ContentType = contentType;
PostData = postData;
}
// 添加https
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)";
//证书设置
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
// end添加https
public string MakeRequest()
{
return MakeRequest("");
}
public string MakeRequest(string parameters)
{
//如果是Https使用证书方式
/*
//设置安全协议
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
//4.5版本以上可以写成
//System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
// 添加https
if (EndPoint.Substring(0, 8) == "https://")
{
//设置证书接受状态
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
// end添加https
//如果使用认证用户密码
//request.Credentials= new NetworkCredential(strUserName, struserPass);
*/
var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
Byte[] tokenByte = Encoding.Default.GetBytes(strUserName + ":" + struserPass);
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
//如果是通过请求头的加密方式访问
//添加请求头 为Basic64加密 这里使用到是 Basic Account:Pwd
//协议认证用户密码
string strUserName = "账户";
string struserPass = "密码";
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(strUserName + ":" + struserPass)));
//request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.POST)//如果传送的数据不为空,并且方法是post
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("UTF-8").GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.PUT)//如果传送的数据不为空,并且方法是put
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("UTF-8").GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
return responseValue;
}
}
public bool CheckUrl(string parameters)
{
bool bResult = true;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
myRequest.Method = Method.ToString(); //设置提交方式可以为"get","head"等
myRequest.Timeout = 10000; //设置网页响应时间长度
myRequest.AllowAutoRedirect = false;//是否允许自动重定向
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
bResult = (myResponse.StatusCode == HttpStatusCode.OK);//返回响应的状态
return bResult;
}
}
}
调用:
static string strPoint = ConfigurationManager.AppSettings["URL"].ToString();
public string RestApi_Get()
{
var client = new RestClient();
client.EndPoint = strPoint;
client.ContentType = "application/json";
client.Method = HttpVerbNew.GET;
var json = client.MakeRequest();
return json;
}
public string RestApi_Get(string strParam)
{
var client = new RestClient();
client.EndPoint = strPoint;
client.ContentType = "application/json";
client.Method = HttpVerbNew.GET;
client.PostData = strParam;
var json = client.MakeRequest(strParam);
return json;
}
public string RestApi_Post(string strParam)
{
var client = new RestClient();
client.EndPoint = strPoint;
client.ContentType = "application/json";
client.Method = HttpVerbNew.POST;
client.PostData = strParam;
var json = client.MakeRequest();
return json;
}
public string RestApi_Put(string id, string strParam)
{
var client = new RestClient();
client.EndPoint = strPoint;
client.ContentType = "application/json";
client.Method = HttpVerbNew.PUT;
client.PostData = strParam;
var json = client.MakeRequest(id);
return json;
}
public string RestApi_Delete(string id)
{
var client = new RestClient();
client.EndPoint = strPoint;
client.ContentType = "application/json";
client.Method = HttpVerbNew.DELETE;
var json = client.MakeRequest(id);
return json;
}
借鉴/原文地址:https://blog.csdn.net/fox009521/article/details/77885141