using AlibabaSDK.Setting;
|
using CommonUtil;
|
using CommonUtil.Web;
|
using Newtonsoft.Json;
|
using Newtonsoft.Json.Linq;
|
using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Net;
|
using System.Security.Cryptography;
|
using System.Text;
|
using CommonUtil;
|
using System.Web;
|
|
|
namespace AlibabaSDK.Api
|
{
|
public class AliabaClient
|
{
|
/// <summary>
|
/// 执行TOP公开API请求
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="request"></param>
|
/// <param name="appKey"></param>
|
/// <param name="secretKey"></param>
|
/// <returns></returns>
|
public static T Execute<T>(IAlibabaApiRequest<T> request, string sessionKey) where T : AlibabaApiResponse
|
{
|
T t = null;
|
try
|
{
|
// request.Validate();
|
string Method = request.GetApiName();
|
string PostUrl = AlibabaApiSet.G1OfficialUrl;
|
string appKey = AlibabaApiSet.AppKey;
|
string secretKey = AlibabaApiSet.SecretKey;
|
long timeStamp = ExtendUtil.EncodeUnixMillisecond(DateTime.Now);
|
//系统级参数
|
string baseUrl = $"{Method}/{appKey}";
|
PostUrl += $"{baseUrl}";
|
//获取应用级参数
|
Dictionary<string, object> paramers = request.GetParameters();
|
paramers.Add("access_token", sessionKey);
|
//计算sign
|
string sign = GetSign(baseUrl, paramers);
|
//paramers.Add("_aop_timestamp", timeStamp.ToString());
|
paramers.Add("_aop_signature", sign);
|
string paramStr = string.Empty;
|
foreach (var pa in paramers)
|
{
|
paramStr += paramStr.IsNullOrEmpty() ? $"?" : "&";
|
Type ty = pa.Value.GetType();
|
if ("string,long,int,douber,decimal".Contains(ty.Name.ToLower()))
|
{
|
paramStr += $"{ pa.Key}={ pa.Value}";
|
}
|
else
|
{
|
paramStr += $"{ pa.Key}={ JSONUtil.ObjectToJson(pa.Value).ToUrlEncode()}";
|
}
|
}
|
IDictionary<string, object> postDic = JSONUtil.JsonToObject<IDictionary<string, object>>(JsonConvert.SerializeObject(paramers));
|
//Post请求数据
|
PostUrl += paramStr;
|
|
//string responseStr = new WebUtil().DoPost(PostUrl, text, null);
|
string responseStr = Post(PostUrl);
|
if (responseStr.IsNullOrEmpty())
|
{
|
return null;
|
}
|
t = JsonConvert.DeserializeObject<T>(responseStr);
|
t.Body = responseStr;
|
}
|
catch (Exception exe)
|
{
|
LogUtil.Error(exe.ToString(), "1688sdk错误");
|
t = request.ErrorObj() as T;
|
if (t != null)
|
{
|
t.ErrorMsg = exe.Message;
|
t.ErrorCode = "-32606";
|
}
|
t.Body = "";
|
}
|
return t;
|
}
|
|
//urlPath: 基础url部分,格式为protocol/apiVersion/namespace/apiName/appKey,如 json/1/system/currentTime/1;如果为客户端授权时此参数置为空串""
|
//paramDic: 请求参数,即queryString + request body 中的所有参数
|
private static string GetSign(string urlPath, Dictionary<string, object> paramDic)
|
{
|
if (urlPath.StartsWith("/"))
|
{
|
urlPath = urlPath.Substring(1, urlPath.Length - 1);
|
}
|
byte[] signatureKey = Encoding.UTF8.GetBytes(AlibabaApiSet.SignKey);//此处用自己的签名密钥
|
List<string> list = new List<string>();
|
foreach (KeyValuePair<string, object> kv in paramDic)
|
{
|
|
Type ty = kv.Value.GetType();
|
if ("string,long,int,douber,decimal".Contains(ty.Name.ToLower()))
|
{
|
list.Add(kv.Key + kv.Value.ToString());
|
}
|
else
|
{
|
list.Add(kv.Key + JSONUtil.ObjectToJson(kv.Value));
|
}
|
}
|
list.Sort();
|
string tmp = urlPath;
|
foreach (string kvstr in list)
|
{
|
tmp = tmp + kvstr;
|
}
|
|
//HMAC-SHA1
|
HMACSHA1 hmacsha1 = new HMACSHA1(signatureKey);
|
byte[] hashBytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(tmp));
|
byte[] hash = hmacsha1.Hash;
|
//TO HEX
|
return BitConverter.ToString(hashBytes).Replace("-", "").ToUpper();
|
}
|
|
public static string Post(string Url)
|
{
|
string strURL = Url;
|
//创建一个HTTP请求
|
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
|
//Post请求方式
|
request.Method = "POST";
|
//内容类型
|
// request.ContentType = "application/x-www-form-urlencoded";
|
|
//设置参数,并进行URL编码
|
|
// string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);
|
|
byte[] payload;
|
//将Json字符串转化为字节
|
// payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
|
//设置请求的ContentLength
|
// request.ContentLength = payload.Length;
|
//发送请求,获得请求流
|
|
Stream writer;
|
try
|
{
|
writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
|
}
|
catch (Exception)
|
{
|
writer = null;
|
Console.Write("连接服务器失败!");
|
}
|
//将请求参数写入流
|
// writer.Write(null, 0, 0);
|
writer.Close();//关闭请求流
|
// String strValue = "";//strValue为http响应所返回的字符流
|
HttpWebResponse response;
|
try
|
{
|
//获得响应流
|
response = (HttpWebResponse)request.GetResponse();
|
}
|
catch (WebException ex)
|
{
|
response = ex.Response as HttpWebResponse;
|
}
|
Stream s = response.GetResponseStream();
|
// Stream postData = Request.InputStream;
|
StreamReader sRead = new StreamReader(s);
|
string postContent = sRead.ReadToEnd();
|
sRead.Close();
|
Console.ForegroundColor = ConsoleColor.Cyan;
|
Console.WriteLine($"服务端返回信息:{postContent},时间:{DateTime.Now.ToString()}");
|
|
|
return postContent;//返回Json数据
|
}
|
}
|
}
|