API問題系列
第一種情況是告訴Server你正在以Json方式呼叫Request,如:
using (WebClient webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8;
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
//webClient.Headers.Add("authorization", "token {apitoken}");
PostData postData = new PostData() { UserId= "Eddie", SystemId="CRM" };
string json = JsonConvert.SerializeObject(postData);
var result = webClient.UploadString("https://jsonbin.org/yowko/test", json);
}
{ UserId: 'Eddie', SystemId:'CRM' }
第二種情況是告訴Web Server你正在對URL中參數編碼Reuqest
,如:
UserId=Eddie&SystemId=CRM
string url= "";
using (WebClient client = new WebClient())
{
System.Collections.Specialized.NameValueCollection postData =
new System.Collections.Specialized.NameValueCollection()
{
{ "para1", para1},
{ "para2", para2},
{ "para3", para3}
};
string pagesource = Encoding.UTF8.GetString(client.UploadValues(url, postData));
}
//ReturnApiData returnFinalApiData = WebAPIModel.GetFinalApi(FinelApiUrl, FinalApiUrlParam);
//ReturnHotelFinalData returnFinalData = WebAPIModel.GetSuccessData<ReturnFinalData>(returnFinalApiData );
public static TResult HttpGet<TParam, TResult>(string address, TParam t)
{
string url = string.Format("{0}?{1}", address, ClassConvertToParam(t));
//HttpContext.Current.Response.Write(url);
using (WebClient wc = new WebClient() { Encoding = Encoding.UTF8 })
{
string srcString = wc.DownloadString(url);
TResult result = JsonConvert.DeserializeObject<TResult>(srcString);
return result;
}
}
/// <summary>取得網際網路資料</summary>
public static TResult HttpPost<TParam, TResult>(string address, TParam t)
{
string url = address;
string postData = "";
if (t.GetType() == typeof(String))
{
postData = t.ToString();
}
else
{
postData = JsonConvert.SerializeObject(t, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
#region 指定 Tls11 , Tls12
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;//Vincent,20180425
#endregion 指定 Tls11 , Tls12
using (WebClient wc = new WebClient() { Encoding = Encoding.UTF8 })
{
//wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.Headers.Add("Content-Type", "application/json");
string srcString = wc.UploadString(url, postData);
TResult result = JsonConvert.DeserializeObject<TResult>(srcString);
return result;
}
}
public static string ClassConvertToParam<T>(T t)
{
StringBuilder sb = new StringBuilder();
foreach (var property in t.GetType().GetProperties())
{
sb.AppendFormat("&{0}={1}", property.Name, property.GetValue(t, null));
}
return sb.ToString().TrimStart('&');
}
public static T GetSuccessData<T>(IEnumerable<object> data)
{
if (data != null && data.Count() > 0)
{
string val;
bool isGeneric = typeof(T).IsGenericType;
if (isGeneric)
{
val = JsonConvert.SerializeObject(data);
}
else
{
val = JsonConvert.SerializeObject(data.FirstOrDefault());
}
//(T)data.ElementAtOrDefault(0);
return JsonConvert.DeserializeObject<T>(val);
}
else
{
return default(T);
}
}
public static T GetSuccessData<T>(ReturnApiData result)
{
if (IsSuccess(result))
{
return GetSuccessData<T>(result.ReturnData);
}
else
{
return default(T);
}
}
public static bool IsSuccess(ReturnApiData result)
{
return result != null &&
result.ReturnStatus.Equals(0) &&
!string.IsNullOrWhiteSpace(result.ReturnMessage) &&
result.ReturnMessage.Equals("成功");
}
元哥的筆記