添加C#sdk

This commit is contained in:
tanghc
2019-04-03 18:00:31 +08:00
parent 8fb4a66109
commit 2cff1a7c0b
35 changed files with 13483 additions and 0 deletions

View File

@@ -0,0 +1,121 @@
using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading.Tasks;
using SDKCSharp.Common;
using SDKCSharp.Request;
using SDKCSharp.Response;
using SDKCSharp.Utility;
namespace SDKCSharp.Client
{
/// <summary>
/// 客户端
/// </summary>
public class OpenClient
{
private static OpenConfig DEFAULT_CONFIG = new OpenConfig();
private static char DOT = '.';
private static char UNDERLINE = '_';
public static String DATA_SUFFIX = "_response";
private Dictionary<string, string> header = new Dictionary<string, string>();
private String url;
private String appId;
private String privateKey;
private OpenConfig openConfig;
private OpenRequest openRequest;
public OpenClient(string url, string appId, string privateKey) : this(url, appId, privateKey, DEFAULT_CONFIG)
{
}
public OpenClient(string url, string appId, string privateKey, OpenConfig openConfig)
{
this.url = url;
this.appId = appId;
this.privateKey = privateKey;
this.openConfig = openConfig;
this.openRequest = new OpenRequest(openConfig);
}
/// <summary>
/// 发送请求
/// </summary>
/// <typeparam name="T">返回的Response类</typeparam>
/// <param name="request">请求对象</param>
/// <returns>返回Response类</returns>
public virtual T Execute<T>(BaseRequest<T> request) where T : BaseResponse
{
return this.Execute<T>(request, null);
}
/// <summary>
/// 发送请求
/// </summary>
/// <typeparam name="T">返回的Response类</typeparam>
/// <param name="request">请求对象</param>
/// <param name="accessToken">accessToken</param>
/// <returns>返回Response类</returns>
public virtual T Execute<T>(BaseRequest<T> request, string accessToken) where T : BaseResponse
{
RequestForm requestForm = request.CreateRequestForm(this.openConfig);
Dictionary<string, string> form = requestForm.Form;
if (!string.IsNullOrEmpty(accessToken))
{
form[this.openConfig.AccessTokenName] = accessToken;
}
form[this.openConfig.AppKeyName] = this.appId;
string content = SopSignature.getSignContent(form);
string sign = RSAUtil.EncryptByPrivateKey(content, this.privateKey);
form[this.openConfig.SignName] = sign;
string resp = this.doExecute(url, requestForm, header);
return this.parseResponse<T>(resp, request);
}
/// <summary>
/// 执行请求
/// </summary>
/// <param name="url">请求url</param>
/// <param name="requestForm">请求内容</param>
/// <param name="header">请求header</param>
/// <returns>返回服务器响应内容</returns>
protected virtual String doExecute(String url, RequestForm requestForm, Dictionary<string, string> header)
{
return openRequest.Request(this.url, requestForm, header);
}
/// <summary>
/// 解析返回结果
/// </summary>
/// <typeparam name="T">返回的Response</typeparam>
/// <param name="resp">服务器响应内容</param>
/// <param name="request">请求Request</param>
/// <returns>返回Response</returns>
protected virtual T parseResponse<T>(string resp, BaseRequest<T> request) where T: BaseResponse {
string method = request.Method;
string dataName = method.Replace(DOT, UNDERLINE) + DATA_SUFFIX;
Dictionary<string, object> jsonObject = JsonUtil.ParseToDictionary(resp);
object data = jsonObject[dataName];
string jsonData = data == null ? "{}" : data.ToString();
T t = JsonUtil.ParseObject<T>(jsonData);
t.Body = jsonData;
return t;
}
}
}

View File

@@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using SDKCSharp.Common;
namespace SDKCSharp.Client
{
public class OpenHttp
{
public const string CONTENT_TYPE_JSON = "application/json";
public const string CONTENT_TYPE_STREAM = "application/octet-stream";
public const string METHOD_POST = "POST";
public CookieContainer cookieContainer = new CookieContainer();
private OpenConfig openConfig;
public OpenHttp(OpenConfig openConfig)
{
this.openConfig = openConfig;
}
public HttpWebRequest CreateWebRequest(string url)
{
return CreateWebRequest(url, null);
}
public HttpWebRequest CreateWebRequest(string url, Dictionary<string, string> header)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieContainer;
request.ContinueTimeout = this.openConfig.ConnectTimeoutSeconds * 1000;
request.ReadWriteTimeout = this.openConfig.ReadTimeoutSeconds * 1000;
bindHeader(request, header);
return request;
}
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string Get(string url, Dictionary<string, string> header)
{
var request = CreateWebRequest(url, header);
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string Get(string url)
{
return Get(url, null);
}
/// <summary>
/// post请求,发送请求体
/// </summary>
/// <param name="url">提交的url</param>
/// <param name="json">json数据</param>
/// <param name="header">header</param>
/// <returns></returns>
public string PostJsonBody(string url, string json, Dictionary<string, string> header)
{
var request = CreateWebRequest(url, header);
request.ContentType = CONTENT_TYPE_JSON;
request.Method = METHOD_POST;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
private void bindHeader(HttpWebRequest request, Dictionary<string, string> header)
{
if (header == null || header.Count == 0)
{
return;
}
ICollection<string> keys = header.Keys;
foreach (string key in keys)
{
request.Headers.Add(key, header[key]);
}
}
/// <summary>
/// post请求并且文件上传
/// </summary>
/// <param name="url">请求url</param>
/// <param name="form">表单数据</param>
/// <param name="header">请求头</param>
/// <param name="files">文件信息</param>
/// <returns></returns>
public string PostFile(string url, Dictionary<string, string> form, Dictionary<string, string> header, List<UploadFile> files)
{
Encoding ENCODING_UTF8 = Encoding.UTF8;
using (MemoryStream memoryStream = new MemoryStream())
{
// 1.分界线
string boundary = string.Format("----{0}", DateTime.Now.Ticks.ToString("x")), // 分界线可以自定义参数
appendBoundary = string.Format("--{0}\r\n", boundary),
endBoundary = string.Format("\r\n--{0}--\r\n", boundary);
byte[] beginBoundaryBytes = ENCODING_UTF8.GetBytes(appendBoundary),
endBoundaryBytes = ENCODING_UTF8.GetBytes(endBoundary);
StringBuilder payload = new StringBuilder();
// 2.组装 上传文件附加携带的参数 到内存流中
if (form != null && form.Count > 0)
{
ICollection<string> keys = form.Keys;
foreach (string key in keys)
{
string boundaryBlock = string.Format("{0}Content-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", appendBoundary, key, form[key]);
byte[] boundaryBlockBytes = ENCODING_UTF8.GetBytes(boundaryBlock);
memoryStream.Write(boundaryBlockBytes, 0, boundaryBlockBytes.Length);
}
}
// 3.组装文件头数据体 到内存流中
foreach (UploadFile uploadFile in files)
{
string boundaryBlock = string.Format("{0}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: application/octet-stream\r\n\r\n", appendBoundary, uploadFile.Name, uploadFile.FileName);
byte[] boundaryBlockBytes = ENCODING_UTF8.GetBytes(boundaryBlock);
memoryStream.Write(boundaryBlockBytes, 0, boundaryBlockBytes.Length);
memoryStream.Write(uploadFile.FileData, 0, uploadFile.FileData.Length);
}
// 4.组装结束分界线数据体 到内存流中
memoryStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
// 5.获取二进制数据,最终需要发送给服务器的数据
byte[] postBytes = memoryStream.ToArray();
// 6.HttpWebRequest 组装
HttpWebRequest webRequest = CreateWebRequest(url, header);
webRequest.Method = METHOD_POST;
webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
webRequest.ContentLength = postBytes.Length;
bindHeader(webRequest, header);
if (Regex.IsMatch(url, "^https://"))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
}
// 7.写入上传请求数据
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(postBytes, 0, postBytes.Length);
}
// 8.获取响应
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), ENCODING_UTF8))
{
string body = reader.ReadToEnd();
return body;
}
}
}
}
static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
}

View File

@@ -0,0 +1,95 @@
using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SDKCSharp.Common;
using SDKCSharp.Utility;
using SDKCSharp.Response;
namespace SDKCSharp.Client
{
public class OpenRequest
{
private const string AND = "&";
private const string EQ = "=";
private const string UTF8 = "UTF-8";
private const string HTTP_ERROR_CODE = "-400";
private OpenConfig openConfig;
private OpenHttp openHttp;
public OpenRequest(OpenConfig openConfig)
{
this.openConfig = openConfig;
this.openHttp = new OpenHttp(openConfig);
}
/// <summary>
/// 请求服务器
/// </summary>
/// <param name="url">url</param>
/// <param name="requestForm">请求表单信息</param>
/// <param name="header">请求头</param>
/// <returns></returns>
public string Request(string url, RequestForm requestForm, Dictionary<string, string> header)
{
return this.doPost(url, requestForm, header);
}
public string doGet(string url, RequestForm requestForm, Dictionary<string, string> header)
{
StringBuilder queryString = new StringBuilder();
Dictionary<string, string> form = requestForm.Form;
Dictionary<string, string>.KeyCollection keys = form.Keys;
foreach (string keyName in keys)
{
queryString.Append(AND).Append(keyName).Append(EQ)
.Append(HttpUtility.UrlEncode(form[keyName].ToString(), Encoding.UTF8));
}
string requestUrl = url + "?" + queryString.ToString().Substring(1);
return this.openHttp.Get(requestUrl);
}
public string doPost(string url, RequestForm requestForm, Dictionary<string, string> header)
{
Dictionary<string, string> form = requestForm.Form;
List<UploadFile> files = requestForm.Files;
if (files != null && files.Count > 0)
{
return this.openHttp.PostFile(url, form, header, files);
}
else
{
return this.openHttp.PostJsonBody(url, JsonUtil.ToJSONString(form), header);
}
}
public string PostJsonBody(string url, string json)
{
return this.openHttp.PostJsonBody(url, json, null);
}
protected string causeException(Exception e)
{
ErrorResponse result = new ErrorResponse();
result.SubCode = HTTP_ERROR_CODE;
result.SubMsg = e.Message;
result.Code = HTTP_ERROR_CODE;
result.Msg = e.Message;
return JsonUtil.ToJSONString(result);
}
}
class ErrorResponse : BaseResponse
{
}
}