您的位置:首页 > 产品设计 > UI/UE

WebRequest请求范例

2016-04-07 13:20 555 查看
WebRequest类是.NET Framework中“请求/响应”模型的abstract基类,用于访问Internet数据。使用WebRequest类请求/响应模型的应用程序可以用协议不可知的方式从Internet请求数据,在这种方式下,应用程序处理WebRequest类的实例,而协议特定的子类则执行请求的具体细节,请求从应用程序发送到某个特定的URI,如服务器上的网页。URI从一个为应用程序注册的WebRequest子类列表中确定要创建的适当子类。注册WebRequest子类通常是为了处理某个特定的协议(如HTTP或FTP),但是也可以注册它以处理对特定服务器或服务器上的路径的请求。

请求回传的数据类型枚举

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebHttp.Common
{
public enum ContentTypeEnum
{
/// <summary>
/// xml
/// </summary>
XML = 0,
/// <summary>
/// json
/// </summary>
JSON = 1
}
}


配置代理服务器的地址

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebHttp.Common
{
public class HttpClientConstant
{
/// <summary>
/// WebProxyHost在configuration中的配置名
/// </summary>
public static string WEB_PROXY_HOST = "WebProxyHost";

/// <summary>
/// WebProxyPort在configuration中的配置名
/// </summary>
public static string WEB_PROXY_PORT = "WebProxyPort";
}
}


请求类接口,定义了Post请求与Get请求

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebHttp.Common
{
public interface IHttpClient
{
/// <summary>
/// post请求体
/// </summary>
/// <param name="url"></param>
/// <param name="strParams">body中的参数</param>
/// <returns></returns>
string DoPost(string url, string strParams);

/// <summary>
/// get请求数据
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
string DoGet(string url);
}
}


请求的具体事项类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WebHttp.Common
{
public class WebHttp : IHttpClient
{
ContentTypeEnum EnumContentType { get; set; }

/// <summary>
/// 如果产生异常时,重试多少次
/// </summary>
int tryTime = 1;
public WebHttp(ContentTypeEnum enumContentType)
{
EnumContentType = enumContentType;
}

/// <summary>
/// 通过Post进行请求
/// </summary>
/// <param name="url"></param>
/// <param name="requestBody"></param>
/// <returns></returns>
public string DoPost(string url, string requestBody)
{
string strResponse = string.Empty;
int getTime = 0;
while (getTime < tryTime)
{
Stream dataStream = null;
StreamReader reader = null;
WebResponse response = null;
try
{
WebRequest request = WebRequest.Create(new Uri(url));
//设置代理
string proxyUrl = ConfigHelper.GetAppSettingsValue(HttpClientConstant.WEB_PROXY_HOST);
int proxyProt = 80;
int.TryParse(ConfigHelper.GetAppSettingsValue(HttpClientConstant.WEB_PROXY_PORT),out proxyProt);
if (!string.IsNullOrEmpty(proxyUrl) && proxyProt != int.MinValue)
{
WebProxy proxy = new WebProxy(proxyUrl, proxyProt);
proxy.UseDefaultCredentials = false;
request.Proxy = proxy;
}
request.ContentType = (EnumContentType == ContentTypeEnum.JSON) ? "text/javascript" : "application/xml";
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream, Encoding.UTF8);
strResponse = reader.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (null != reader)
{
reader.Close();
reader.Dispose();
}
if (null != dataStream)
{
dataStream.Close();
dataStream.Dispose();
}
if (null != response)
response.Close();
getTime += 1;
}
}
return strResponse;

}

/// <summary>
/// 通过Get方式进行请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string DoGet(string url)
{
string response = string.Empty;
int getTime = 0;
while (getTime < tryTime)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//request.UserAgent = "Opera/9.25 (Windows NT 6.0; U; en)";
request.KeepAlive = true;
//request.Timeout = 6000*1000;
string proxyUrl = ConfigHelper.GetAppSettingsValue(HttpClientConstant.WEB_PROXY_HOST);
int proxyProt = 80;
int.TryParse(ConfigHelper.GetAppSettingsValue(HttpClientConstant.WEB_PROXY_PORT), out proxyProt);
if (!string.IsNullOrEmpty(proxyUrl) && proxyProt != int.MinValue)
{
WebProxy proxy = new WebProxy(proxyUrl, proxyProt);
proxy.UseDefaultCredentials = false;
request.Proxy = proxy;
}

HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应,那么继续等待相应
continue;
StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
response = sr.ReadToEnd().Trim();
resp.Close();
sr.Close();
break;
}
catch (WebException ex)
{
throw ex;
}
finally
{
getTime += 1;
}
}
return response;
}
}
}


实现类的抽象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebHttp.WechatEnterpriseService
{
public abstract class IWechatEnterpriseService<TRequest, TResponse>
{
/// <summary>
/// 编码格式
/// </summary>
protected ContentTypeEnum ContentTypeEnum { get; set; }

/// <summary>
/// Web调用实体
/// </summary>
protected IHttpClient WebClient { get; set; }

/// <summary>
/// 应用套件令牌
/// </summary>
protected string SuiteAccessToken { get; set; }

/// <summary>
/// 微信接口服务url,如果url后面有参数,需要一起带进来
/// </summary>
protected string ServiceURL { get; set; }
/// <summary>
/// 请的实体信息
/// </summary>
protected TRequest tRequest { get; set; }
/// <summary>
/// 返回的实体信息
/// </summary>
protected TResponse tResponse { get; set; }
/// <summary>
/// 服务的主域名URL
/// </summary>
protected string ServiceMainURL { get; set; }

/// <summary>
/// 日志中使用的Inferface名称
/// </summary>
protected string InterfaceName = "Corp.WechatEnterprise.Service.IWechatEnterpriseService";

public IWechatEnterpriseService()
{
ContentTypeEnum = ContentTypeEnum.JS
b826
ON;
WebClient = new WebHttp(ContentTypeEnum);
ServiceMainURL = ConfigHelper.GetAppSettingsValue(ConfigConstValue.SERVICE_URL);
}

/// <summary>
/// 请求返回实体,使用Post方法
/// </summary>
/// <param name="tRequest"></param>
/// <param name="url"></param>
/// <returns></returns>
protected virtual void GetRequestByPost()
{
tResponse = default(TResponse);
string jsonParams = string.Empty;
string response = string.Empty;
try
{
if (null != tRequest)
{
ServiceURL = ServiceMainURL.EndsWith("/") ? ServiceMainURL + ServiceURL : string.Format("{0}/{1}", ServiceMainURL, ServiceURL);
ContentTypeEnum contentTypeEnum = ContentTypeEnum.JSON;
IHttpClient httpClient = new WebHttp(contentTypeEnum);
jsonParams = JsonHelper.Serialize(tRequest);
response = httpClient.DoPost(ServiceURL, jsonParams);
if (!string.IsNullOrEmpty(response))
tResponse = JsonHelper.Deserialize<TResponse>(response);
}
}
catch (Exception ex)
{
throw ex;
}
}

/// <summary>
/// 请求返回实体,使用Get方法
/// </summary>
/// <param name="tRequest"></param>
/// <param name="url"></param>
/// <returns></returns>
protected virtual void GetRequestByGet()
{
tResponse = default(TResponse);
string response = string.Empty;
try
{
ServiceURL = ServiceMainURL.EndsWith("/") ? ServiceMainURL + ServiceURL : string.Format("{0}/{1}", ServiceMainURL, ServiceURL);
ContentTypeEnum contentTypeEnum = ContentTypeEnum.JSON;
IHttpClient httpClient = new WebHttp(contentTypeEnum);
response = httpClient.DoGet(ServiceURL);
if (!string.IsNullOrEmpty(response))
tResponse = JsonHelper.Deserialize<TResponse>(response);
}
catch (Exception ex)
{
throw ex;
}
}
}
}


具体的实现类,现在以微信提供URL接口为例。有新的通过URL请求的,以下面的请求为蓝本进行构造:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebHttp.WechatEnterpriseContract;
using WebHttp.Common;
namespace WebHttp.WechatEnterpriseService
{
/// <summary>
/// 企业号access_token
/// </summary>
public class AccessTokenService : IWechatEnterpriseService<AccessTokenRequest, AccessTokenResponse>
{
/// <summary>
/// 获取企业号的永久授权码
/// </summary>
/// <returns></returns>
public AccessTokenResponse GetAccessToken(AccessTokenRequest accessTokenRequest, string suiteAccessToken)
{
string getUrl = string.Format("cgi-bin/service/get_corp_token?suite_access_token={0}", suiteAccessToken);
base.ServiceURL = getUrl;
base.tRequest = accessTokenRequest;
base.GetRequestByPost();
return base.tResponse;
}
}
}


请求返回的参数实体:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebHttp.WechatEnterpriseContract
{
/// <summary>
/// 企业号access_token请求/回传契约
/// </summary>
[Serializable]
public class AccessTokenRequest
{
/// <summary>
/// 应用套件id
/// </summary>
public string suite_id { get; set; }

/// <summary>
/// 授权方corpid
/// </summary>
public string auth_corpid { get; set; }

/// <summary>
/// 永久授权码,通过get_permanent_code获取
/// </summary>
public string permanent_code { get; set; }
}
[Serializable]
public class AccessTokenResponse
{
/// <summary>
/// 授权方(企业)access_token
/// </summary>
public string access_token { get; set; }

/// <summary>
/// 授权方(企业)access_token超时时间
/// </summary>
public string expires_in { get; set; }
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息