WebApiTools.cs - WebApi客户端调用Web Api接口工具类
WebApiTools类接口方法
WebApiTools类完整代码
C# 全选
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
namespace CSFramework.WebApi.Core
{
/// <summary>
/// WebApi客户端调用工具类
/// </summary>
public static class WebApiTools
{
static WebApiTools()
{
WebApiTools.TimeOut = 5 * 60 * 1000;//3分钟超时
}
/// <summary>
/// Http请求超时时间
/// </summary>
public static int TimeOut { get; set; }
/// <summary>
/// 预设的POST方法
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string Post(string url, string data)
{
return Post(url, data, "application/json;charset=UTF-8");
}
/// <summary>
/// 预设的GET方法
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string Get(string url, string param)
{
return Get(url, param, "text/html;charset=UTF-8");
}
/// <summary>
/// 客户端统一提交数据
/// </summary>
/// <param name="url">WebAPI核心URL地址</param>
/// <param name="data">提交的数据</param>
/// <param name="contentType">指定request.ContentType</param>
/// <returns>返回数据</returns>
public static string Post(string url, string data, string contentType)
{
string returnData = null;
try
{
string strURL = url;
System.Net.HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.CheckCertificateRevocationList = false;
ServicePointManager.DefaultConnectionLimit = 512;
ServicePointManager.Expect100Continue = false;
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
request.KeepAlive = false;
}
else
{
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
}
request.Method = "POST";
request.ContentType = contentType;// "application/json;charset=UTF-8";//POST必须使用JSON格式
string paraUrlCoded = data;
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
request.Timeout = WebApiTools.TimeOut;
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.GetEncoding("utf-8"));
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
returnData = strValue;
return returnData.Trim() + "\n";
}
catch (WebException ex)
{
string result = "POST:操作失败!\r\n" + ex.Message;
if (ex.Response != null)
result = result + "\r\n" + GetResponseText(ex.Response);
throw new Exception(result);
}
catch (Exception ex)
{
throw new Exception("POST:操作失败!\r\n" + ex.Message);
}
}
private static string GetResponseText(WebResponse response)
{
string text;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
if ((response is HttpWebResponse))
{
int status = (int)(response as HttpWebResponse).StatusCode;
if (status == 429) text = "流量访问限制!" + text;
}
return text;
}
/// <summary>
/// 客户端统一提交数据
/// </summary>
/// <param name="url">WebAPI核心URL地址</param>
/// <param name="param">URL参数</param>
/// <returns>返回数据</returns>
public static string Get(string url, string param, string contentType)
{
try
{
System.Net.HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.CheckCertificateRevocationList = false;
ServicePointManager.DefaultConnectionLimit = 512;
ServicePointManager.Expect100Continue = false;
request = WebRequest.Create(url + (param == "" ? "" : "?") + param) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
request.KeepAlive = false;
}
else
{
request = (System.Net.HttpWebRequest)WebRequest.Create(url + (param == "" ? "" : "?") + param);
}
//request = (HttpWebRequest)WebRequest.Create(url + (param == "" ? "" : "?") + param);
request.Method = "GET";
request.ContentType = contentType;//text/html;charset=UTF-8;
#region 获取网页内容太大的话,就加下面这两句代码
request.Headers["Accept-Encoding"] = "gzip,deflate";
request.AutomaticDecompression = DecompressionMethods.GZip;
#endregion
request.Timeout = WebApiTools.TimeOut;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
catch (WebException ex)
{
string result = "GET:操作失败!\r\n" + ex.Message;
if (ex.Response != null)
result = result + "\r\n" + GetResponseText(ex.Response);
throw new Exception(result);
}
catch (Exception ex)
{
throw new Exception("GET:操作失败!\r\n" + ex.Message);
}
}
/// <summary>
/// 获取图片资源
/// </summary>
/// <param name="url">图片网址</param>
/// <returns></returns>
public static Image GetImage(string url)
{
try
{
var request = WebRequest.Create(url);
request.Timeout = WebApiTools.TimeOut;
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
return Bitmap.FromStream(stream);
}
}
}
catch
{
return null;
}
}
/// <summary>
/// 获取服务器请求,返回Stream对象。
/// </summary>
/// <param name="url">服务器地址</param>
/// <param name="param">URL参数</param>
/// <param name="contentType"></param>
/// <returns></returns>
public static Stream GetResponse(string url, string param, string contentType)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (param == "" ? "" : "?") + param);
request.Method = "GET";
request.ContentType = contentType;//text/html;charset=UTF-8;
#region 获取网页内容太大的话,就加下面这两句代码
request.Headers["Accept-Encoding"] = "gzip,deflate";
request.AutomaticDecompression = DecompressionMethods.GZip;
#endregion
request.Timeout = WebApiTools.TimeOut;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
return myResponseStream;
}
catch(Exception ex)
{
throw ex;
}
}
/// <summary>
/// 将对象转换为URL参数格式,如:id=11111&name=www.cscode.net
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public static string GetUrlParam(Object instance)
{
StringBuilder sb = new StringBuilder("");
PropertyInfo[] pi = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
object value = null;
foreach (PropertyInfo p in pi)
{
value = p.GetValue(instance, null);
if (sb.Length == 0)
sb.Append(p.Name + "=" + (value == null ? "" : value.ToString()));
else
sb.Append("&" + p.Name + "=" + (value == null ? "" : value.ToString()));
}
return sb.ToString();
}
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网