/// <summary>
/// WPS API接口调用
/// </summary>
/// <param name="requestMethod">请求方式(get,post,put,delete)</param>
/// <param name="requestUri">接口uri</param>
/// <param name="bodyJson">请求数据(json格式)</param>
/// <returns>响应内容(json格式)</returns>
public static string RequestUrl(string requestMethod, string requestUri, string bodyJson)
{
#region 验证参数有效性
if (!methodArr.Any(w => w == requestMethod))
{
throw new Exception($"requestMethod参数只能为get或post或put或delete");
}
if (string.IsNullOrWhiteSpace(requestUri))
{
throw new Exception($"requestUri参数不能为空");
}
#endregion
var contentType = "application/json";
//由于接口需要格林威治时间故将当前时间转为格林威治时间再将格林威治时间字符串转成日期类型传入头部
var nowDateStr = DateTime.Now.ToString("r");
var nowTimeGMT = DateTime.Parse(nowDateStr);
var utf8 = Encoding.UTF8;
var contentMd5To16Hex = Convert16Hex(EncryptUtils.MD5Encrypt(string.IsNullOrWhiteSpace(bodyJson) ? requestUri : bodyJson, utf8));
var sha1Str = SHA1($"{ConstantsCRM.WpsApiAppSecrect}{contentMd5To16Hex}{contentType}{nowDateStr}", utf8).ToLower();
var headerAuthorization = $"WPS:{ConstantsCRM.WpsApiAppId}:{sha1Str}";
var url = $"{ConstantsCRM.WpsApiUrlRoot}{requestUri}";
#region 执行请求
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = requestMethod;
req.Headers.Add("Authorization", headerAuthorization);
req.Headers.Add("Content-Md5", contentMd5To16Hex);
req.ContentType = contentType;
req.Date = nowTimeGMT;
if (requestMethod == "post")
{
byte[] bytes = utf8.GetBytes(bodyJson);
req.ContentLength = bytes.Length;
Stream reqstream = req.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
}
string result = string.Empty;
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream(), utf8))
{
result = sr.ReadToEnd();
}
}
catch (Exception ex)
{
result = JsonConvert.SerializeObject(new BaseOut()
{
status = 0,
msg = ex.Message
});
}
#endregion
return result;
}
public static string Convert16Hex(string input)
{
StringBuilder sb = new StringBuilder();
//便利数组中元素转化成字符并拼接
for (int I = 0; I < input.Length; I++)
{
//X 表是10进制,X2表示16进制
sb.AppendFormat("{0:X2}", input[I]);
}
return sb.ToString();
}
#region SHA1 加密,返回大写字符串
/// <summary>
/// SHA1 加密,返回大写字符串
/// </summary>
/// <param name="content">需要加密字符串</param>
/// <param name="encode">指定加密编码</param>
/// <returns>返回40位大写字符串</returns>
public static string SHA1(string content, Encoding encode)
{
try
{
SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] bytes_in = encode.GetBytes(content);
byte[] bytes_out = sha1.ComputeHash(bytes_in);
sha1.Dispose();
string result = BitConverter.ToString(bytes_out);
result = result.Replace("-", "");
return result;
}
catch (Exception ex)
{
throw new Exception($"SHA1加密出错:{ex.Message}");
}
}
#endregion