程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成快遞api接口挪用辦法

C#完成快遞api接口挪用辦法

編輯:C#入門知識

C#完成快遞api接口挪用辦法。本站提示廣大學習愛好者:(C#完成快遞api接口挪用辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成快遞api接口挪用辦法正文


無平台限制,依附於快遞api網接口

  ----------------實體類
  [DataContract]
  public class SyncResponseEntity
  {
    public SyncResponseEntity() { }
    /// <summary>
    /// 須要查詢的快遞代號
    /// </summary>
    [DataMember(Order = 0, Name = "id")]
    public string ID { get; set; }
 
    /// <summary>
    /// 須要查詢的快遞稱號
    /// </summary>
    [DataMember(Order = 1, Name = "name")]
    public string Name { get; set; }
 
    /// <summary>
    /// 須要查詢的快遞單號
    /// </summary>
    [DataMember(Order = 2, Name = "order")]
    public string Order { get; set; }
 
    /// <summary>
    /// 新聞內容
    /// </summary>
    [DataMember(Order = 5, Name = "message")]
    public string Message { get; set; }
 
    /// <summary>
    /// 辦事器狀況
    /// </summary>
    [DataMember(Order = 6, Name = "errcode")]
    public string ErrCode { get; set; }
 
    /// <summary>
    /// 運單狀況
    /// </summary>
    [DataMember(Order = 7, Name = "status")]
    public int Status { get; set; }
 
    /// <summary>
    /// 跟蹤記載
    /// </summary>
    [DataMember(Order = 8, Name = "data")]
    public List<Order> Data { get; set; }
  }
 
  [DataContract(Name = "data")]
  public class Order
  {
    public Order() { }
    public Order(string time, string content)
    {
      this.Time = time;
      this.Content = content;
    }
 
    [DataMember(Order = 0, Name = "time")]
    public string Time { get; set; }
 
    [DataMember(Order = 1, Name = "content")]
    public string Content { get; set; }
 
  }
 
---------挪用辦法
public static int uid = Utils.GetAppConfig<int>("KUAIDIAPI_UID", 0);
    public static string sync_url = Utils.GetAppConfig<string>("KUAIDIAPI_SYNC_URL", string.Empty);
    public static string key = Utils.GetAppConfig<string>("KUAIDIAPI_KEY", string.Empty);
 
    /// <summary>
    /// 同步單號查詢辦法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="id"></param>
    /// <param name="order"></param>
    /// <param name="isSign"></param>
    /// <param name="isLast"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static T APIQueryDataSYNC<T>(string id,
                       string order,
                       bool isSign,
                       bool isLast,
                       T defaultValue)
    {
      try
      {
        string currTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string currKey = key;
        if (isSign)
        {
          currKey = Utils.GetSign(uid, key, id, order, currTime);
          currKey += "&issign=true";
        }
 
        string url = sync_url + string.Format("?uid={0}&key={1}&id={2}&order={3}&time={4}",
                      uid, currKey, id, order, HttpUtility.UrlEncode(currTime));
 
        string html = Utils.GET_WebRequestHTML("utf-8", url);
 
        if (!string.IsNullOrEmpty(html))
          return Utils.JsonToObj<T>(html, defaultValue);
      }
      catch (Exception ex)
      {
        throw new Exception(ex.Message);
      }
 
      return defaultValue;
    }
 
  }
 
  /// <summary>
  /// 幫助對象類
  /// </summary>
  public class Utils
  {
    public static string GetSign(int uid, string key, string id, string order, string time)
    {
      string sign = string.Format("uid={0}&key={1}&id={2}&order={3}&time={4}",
                    uid,
                    key,
                    id,
                    HttpUtility.UrlEncode(order.ToLower()),
                    HttpUtility.UrlEncode(time));
 
      return Md5Encrypt(sign.ToLower(), "utf-8");
    }
 
    public static string Md5Encrypt(string strToBeEncrypt, string encodingName)
    {
      MD5 md5 = new MD5CryptoServiceProvider();
      Byte[] FromData = System.Text.Encoding.GetEncoding(encodingName).GetBytes(strToBeEncrypt);
      Byte[] TargetData = md5.ComputeHash(FromData);
      string Byte2String = "";
      for (int i = 0; i < TargetData.Length; i++)
      {
        Byte2String += TargetData[i].ToString("x2");
      }
      return Byte2String;
    }
 
    public static T GetRequest<T>(string key, T defaultValue)
    {
      string value = HttpContext.Current.Request[key];
 
      if (string.IsNullOrEmpty(value))
      {
        return defaultValue;
      }
      else
      {
        try
        {
          return (T)Convert.ChangeType(value, typeof(T));
        }
        catch
        {
          return defaultValue;
        }
      }
    }
 
    public static T GetAppConfig<T>(string key, T defaultValue)
    {
      string value = ConfigurationManager.AppSettings[key];
 
      if (string.IsNullOrEmpty(value))
      {
        return defaultValue;
      }
      else
      {
        try
        {
          return (T)Convert.ChangeType(value, typeof(T));
        }
        catch
        {
          return defaultValue;
        }
      }
    }
 
    public static string ObjToJson<T>(T data)
    {
      try
      {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(data.GetType());
        using (MemoryStream ms = new MemoryStream())
        {
          serializer.WriteObject(ms, data);
          return Encoding.UTF8.GetString(ms.ToArray());
        }
      }
      catch
      {
        return null;
      }
    }
 
    public static T JsonToObj<T>(string json, T defaultValue)
    {
      try
      {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
          object obj = serializer.ReadObject(ms);
 
          return (T)Convert.ChangeType(obj, typeof(T));
        }
      }
      catch
      {
        return defaultValue;
      }
    }
 
    public static T XmlToObj<T>(string xml, T defaultValue)
    {
      try
      {
        System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
          object obj = serializer.ReadObject(ms);
 
          return (T)Convert.ChangeType(obj, typeof(T));
        }
      }
      catch
      {
        return defaultValue;
      }
    }
 
    public static string ObjToXml<T>(T data)
    {
      System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
      using (MemoryStream ms = new MemoryStream())
      {
        serializer.WriteObject(ms, data);
        return Encoding.UTF8.GetString(ms.ToArray());
 
      }
    }
 
    public static string GET_WebRequestHTML(string encodingName, string htmlUrl)
    {
      string html = string.Empty;
 
      try
      {
        Encoding encoding = Encoding.GetEncoding(encodingName);
 
        WebRequest webRequest = WebRequest.Create(htmlUrl);
        HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
        Stream responseStream = httpWebResponse.GetResponseStream();
        StreamReader streamReader = new StreamReader(responseStream, encoding);
 
        html = streamReader.ReadToEnd();
 
        httpWebResponse.Close();
        responseStream.Close();
        streamReader.Close();
      }
      catch (WebException ex)
      {
        throw new Exception(ex.Message);
      }
 
      return html;
    }
 
    /// <summary>
    /// 將網址類容轉換成文本字符串 post要求
    /// </summary>
    /// <param name="data">要post的數據</param>
    /// <param name="url">目的url</param>
    /// <returns>辦事器呼應</returns>
    public static string POST_HttpWebRequestHTML( string encodingName,
                           string htmlUrl,
                           string postData)
    {
      string html = string.Empty;
 
      try
      {
        Encoding encoding = Encoding.GetEncoding(encodingName);
 
        byte[] bytesToPost = encoding.GetBytes(postData);
 
        WebRequest webRequest = WebRequest.Create(htmlUrl);
        HttpWebRequest httpRequest = webRequest as System.Net.HttpWebRequest;
 
        httpRequest.Method = "POST";
        httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        httpRequest.ContentLength = bytesToPost.Length;
        httpRequest.Timeout = 15000;
        httpRequest.ReadWriteTimeout = 15000;
        Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytesToPost, 0, bytesToPost.Length);
        requestStream.Close();
 
        HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
        Stream responseStream = httpWebResponse.GetResponseStream();
        StreamReader streamReader = new StreamReader(responseStream, encoding);
 
        html = streamReader.ReadToEnd();
      }
      catch (WebException ex)
      {
        throw new Exception(ex.Message);
      }
 
      return html;
    }
  }
 
  /// <summary>
  /// 接口類型
  /// </summary>
  public enum APIType
  {
    //同步查詢
    SYNC = 1
  }

根本上代碼都在下面。在帶www.kuaidiapi.cn上請求一個uid就年夜功樂成。

以上所述就是本文的全體內容了,願望年夜家可以或許愛好。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved