using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Jayrock.Json.Conversion;
using YouZanSDKStandard.Api.Request;
using YouZanSDK.Setting;
using CommonUtil.Web;
using CommonUtil;
namespace YouZanSDKStandard.Api
{
public class YouZanClient
{
///
/// 调用接口
///
///
///
///
public static T Execute(IRequest request) where T : YouZanResponse
{
return Execute(request, string.Empty);
}
///
/// 调用接口
///
///
///
///
///
public static T Execute(IRequest request, string SessionKey) where T : YouZanResponse
{
T t = null;
#region 检验参数
request.Validate();
#endregion
//接口参数
IDictionary dict = request.GetParameters();
//Dictionary dict = new Dictionary();
//foreach (var dic in dictionary)
//{
// dict.Add(dic.Key, dic.Value);
//}
string reStr = "";
YouZanResponse rspBase = null;
try
{
string apiUrl = YouZanSetting.GetApiUrl(request.GetApiName(), request.GetApiVersion(), SessionKey);
//reStr = PostJson(apiUrl, dict);
reStr = new WebUtil().DoPostWithJson(apiUrl, dict, null);
//if (!reStr.Contains("true"))
// LogTextHelper.WriteLine("有赞接口返回错误信息", reStr);
try
{
//rspBase = JsonConvert.Import(typeof(YouZanResponse), reStr) as YouZanResponse;
rspBase = JSONUtil.JsonToObject(reStr);
}
catch (Exception e)
{
LogTextHelper.WriteLine("有赞接口转换错误", reStr);
}
if (rspBase != null)
{
if (rspBase.success)
{
try
{
reStr = request.ResponseJsonPrefix(reStr);
// t = JsonConvert.Import(typeof(T), reStr) as T;
t= JSONUtil.JsonToObject(reStr);
}
catch (Exception ex)
{
LogTextHelper.WriteLine("有赞接口转换错误1", reStr);
rspBase = new YouZanResponse
{
code = 500,
success = false,
message = "接口调用异常" + ex.ToString() + "接口返回:" + reStr,
};
t = (T)rspBase;
}
}
else
{
reStr = request.ResponseJsonPrefix(reStr);
t = JSONUtil.JsonToObject(reStr);
}
}
else
{
rspBase = new YouZanResponse
{
code = 500,
success = false,
message = "接口调用异常接口返回:" + reStr,
};
t = (T)rspBase;
}
}
catch (Exception ex)
{
rspBase = new YouZanResponse
{
code = 500,
success = false,
message = "接口调用异常" + ex.ToString() + "接口返回:" + reStr,
};
t = (T)rspBase;
}
if (t == null)
{
rspBase = new YouZanResponse
{
code = 500,
success = false,
message = "接口调用异常接口返回:" + reStr,
};
t = (T)rspBase;
}
return t;
#region 旧sdk废弃
/*
//youzan.items.get 长度16
int num = apiName.LastIndexOf(".");//num=12
string text = apiName.Substring(0, num);//text="youzan.items"
string text2 = apiName.Substring(num + 1, apiName.Length - (num + 1));//text2="get"
string postUrl = YouZanSetting.OfficialCallUrl + "/" + text + "/3.1.0/" + text2;
string postPar = "?access_token=" + SessionKey;
if (dictionary.Count > 0)
{
foreach (var item in dictionary )
{
postPar += "&" + item.Key + "=" + item.Value;
}
}
// string reStr = postMethod(postUrl, postPar, false);
Auth auth = new Token(SessionKey);
YZClient yzClient = new DefaultYZClient(auth);
string reStr="" ;
switch (apiName)
{
case "youzan.scrm.customer.search": reStr = yzClient.Invoke(apiName, "3.1.0", "Post", dict, null); ; break;
case "youzan.trades.sold.outer.get": reStr = yzClient.Invoke(apiName, "3.0.0", "get", dict, null); ; break;
case "youzan.trades.sold.get": reStr = yzClient.Invoke(apiName, "4.0.0", "get", dict, null); ; break;
}
YouZanResponse rspBase;
try
{
rspBase = JsonConvert.Import(typeof(YouZanResponse), reStr) as YouZanResponse;
if (rspBase != null)
{
if (rspBase.error_response != null)
{
rspBase.IsError = true;
}
#region 返回值处理
if (rspBase.IsError)
{
t = (T) rspBase;
}
else
{
#region Response对象处理
try
{
reStr = request.ResponseJsonPrefix(reStr);
t = JsonConvert.Import(typeof(T), reStr) as T;
}
catch(Exception ex)
{
string exStr = ex.ToString();
}
#endregion
}
#endregion
}
else
{
rspBase = new YouZanResponse
{
IsError = true,
error_response = {msg = "接口调用异常"}
};
t = (T)rspBase;
}
}
catch (Exception ex)
{
rspBase = new YouZanResponse
{
IsError = true,
error_response = { msg = "接口调用异常" }
};
t = (T) rspBase;
}
return t;
*/
#endregion
}
///
/// post调用求情
///
/// 请求地址
/// 请求参数
///
///
private static string postMethod(string postUrl, string pars, bool isLogin = false)
{
byte[] postData = System.Text.Encoding.UTF8.GetBytes(pars);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(postUrl);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "post";
request.Timeout = 5000;
request.ContentLength = postData.Length;
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(postData, 0, postData.Length);
requestStream.Close();
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
var ecoding = isLogin ? Encoding.Default : Encoding.UTF8;
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), ecoding);
string str = sr.ReadToEnd();//读取获取到的参数
sr.Close();
response.Close();
return str;
}
///
/// PostJson请求
///
///
///
///
public static string PostJson(string url, object postObj)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var postData = Jayrock.Json.Conversion.JsonConvert.ExportToString(postObj);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
public static string PostJsonSpecial(string url, string postData)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
}
}