根据网上的文章整理了下。
先定义几个枚举
/// <summary>
/// HTTP访问method 常用的几样
/// </summary>
public enum HttpVerb
{
/// <summary>
/// get:获取
/// </summary>
GET,
/// <summary>
/// post:修改
/// </summary>
POST,
/// <summary>
/// put:写入
/// </summary>
PUT,
/// <summary>
/// delete:删除
/// </summary>
DELETE
}
/// <summary>
/// HTTP访问格式类型,根据Postman整理
/// </summary>
public enum HttpContentType
{
/// <summary>
/// text/plain
/// </summary>
Text,
/// <summary>
/// application/json
/// </summary>
JSON,
/// <summary>
/// application/xml
/// </summary>
XML,
/// <summary>
/// text/xml
/// </summary>
TextXML,
/// <summary>
/// text/html
/// </summary>
HTML,
/// <summary>
/// application/javascript
/// </summary>
Javascript
}
定义RestHelper
/// <summary>
/// Rest方式访问方法,ContentType为application/json
/// </summary>
public class RestHelper
{
/// <summary>
/// 请求的url地址 eg: http://215.23.12.45:8080/order?order_id=1&isdel=0
/// </summary>
public string EndPoint { get; set; }
/// <summary>
/// 请求的方法,默认 GET
/// </summary>
public HttpVerb Method { get; set; }
/// <summary>
/// 格式类型:默认application/json
/// </summary>
public HttpContentType ContentType { get; set; }
/// <summary>
/// 传送的数据,如json字符串
/// </summary>
public string PostData { get; set; }
/// <summary>
/// 编码规范,默认 UTF8
/// </summary>
public Encoding HttpEncoding { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public RestHelper(HttpContentType contentType = HttpContentType.JSON)
{
EndPoint = "";
Method = HttpVerb.GET;
ContentType = contentType;
PostData = "";
HttpEncoding = Encoding.UTF8;
}
/// <summary>
/// 构造函数
/// </summary>
public RestHelper(string endpoint, HttpContentType contentType = HttpContentType.JSON)
{
EndPoint = endpoint;
Method = HttpVerb.GET;
ContentType = contentType;
PostData = "";
HttpEncoding = Encoding.UTF8;
}
/// <summary>
/// 构造函数
/// </summary>
public RestHelper(string endpoint, HttpVerb method, HttpContentType contentType = HttpContentType.JSON)
{
EndPoint = endpoint;
Method = method;
ContentType = contentType;
PostData = "";
HttpEncoding = Encoding.UTF8;
}
/// <summary>
/// 构造函数
/// </summary>
public RestHelper(string endpoint, HttpVerb method, string postData, HttpContentType contentType = HttpContentType.JSON)
{
EndPoint = endpoint;
Method = method;
ContentType = contentType;
PostData = postData;
HttpEncoding = Encoding.UTF8;
}
/// <summary>
/// 构造函数
/// </summary>
public RestHelper(string endpoint, Encoding encoding, HttpVerb method= HttpVerb.GET, string postData="", HttpContentType contentType = HttpContentType.JSON)
{
EndPoint = endpoint;
Method = method;
ContentType = contentType;
PostData = postData;
HttpEncoding = encoding;
}
/// <summary>
/// 直接访问
/// </summary>
/// <returns></returns>
public string MakeRequest()
{
return MakeRequest("");
}
/// <summary>
/// 带参数访问,如 MakeRequest("?param=0")
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public string MakeRequest(string parameters)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = GetContentType(ContentType);
//如果传送的数据不为空,并且方法是post或put
if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT))
{
var bytes = HttpEncoding.GetBytes(PostData);//编码方式,默认UTF-8
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
//if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.PUT)//如果传送的数据不为空,并且方法是put
//{
// var bytes = HttpEncoding.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;
}
}
catch(Exception e)
{
throw new Exception("Request failed.>>" + CommonHelper.GetException(e));
}
}
/// <summary>
/// 将content type转成字符串描述
/// </summary>
/// <param name="contentType"></param>
/// <returns></returns>
private string GetContentType(HttpContentType contentType)
{
switch (contentType)
{
case HttpContentType.Text:
return "text/plain";
case HttpContentType.JSON:
return "application/json";
case HttpContentType.XML:
return "application/xml";
case HttpContentType.TextXML:
return "text/xml";
case HttpContentType.HTML:
return "text/html";
case HttpContentType.Javascript:
return "application/javascript";
default:
return "";
}
}
}
使用
string URL = "http://localhost:7724/api/SnInfo?sn=sn00111&chuteno=111";
URL = txtUrl.Text;
get
//RestHelper rest = new RestHelper(URL);
//string result = rest.MakeRequest();
//lblResult.Text = result;
RestHelper rest = new RestHelper(URL, HttpVerb.POST);
List<SN_Info> lstSn = new List<SN_Info>();
SN_Info sn = new SN_Info();
sn.SN = "sn222";
sn.ChuteNo = "222";
lstSn.Add(sn);
sn = new SN_Info();
sn.SN = "sn223";
sn.ChuteNo = "223";
lstSn.Add(sn);
string data = JsonHelper.Serialize(lstSn);//@"[{SN:""sn122"",ChuteNo:""122""},{SN:""123"",ChuteNo:""123""}]";
rest.PostData = data;
string strResult = rest.MakeRequest();
ResResult res = JsonHelper.Deserialize<ResResult>(strResult);
lblResult.Text = res.Message;
参考:
https://blog.csdn.net/zhifeiya/article/details/12308493