Api程序接口對接


先看一下參數表和參數示例

 

首先是參數,我們而已發現,json數據成層級方式顯示,所以我們先以層級關系為主 定義類(從圖中可以發現一共存在6個類):定義類的時候我們需要把子級類也定義出來(標黃部分)。這里定義的類只是請求參數的類

 

 public class L_Lable
    {
        //Lable
        public L_Data Data { get; set; }
        public string Requestld { get; set; }
        public string RequestTime { get; set; }
        public string Version { get; set; }
    }



public class L_Data
    {
        
        public string OrderID { get; set; }
        public L_ParcelInformation ParcelInformation { get; set; } public L_RecipientAddress RecipientAddress { get; set; }
        public string ChannelName { get; set; }
        public string Token { get; set; }
        public string ServiceTypeCode { get; set; }
        public string WarehouseCode { get; set; }
        public string LabelMarkText { get; set; }
        public L_RedundancyField RedundancyField { get; set; }

    }


public class L_ParcelInformation
    {
        public string Weight { get; set; }
        public string WeightUnit { get; set; }
        public string Length { get; set; }
        public string Width { get; set; }
        public string Height { get; set; }
        public string SizeUnit { get; set; }
        public string ExistDangerousGoods { get; set; }
        public L_ProductInformations ProductInformations { get; set; }
    }


 public class L_RecipientAddress
    {
        //L_RecipientAddress
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Company { get; set; }
        public string StreetAddress { get; set; }
        public string StreetAddress2 { get; set; }
        public string StreetAddress3 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZIPCode { get; set; }
        public string Country { get; set; }
        public string PhoneNumber { get; set; }
        public string PhoneExtension { get; set; }
        public string Email { get; set; }
        public string IsResidential { get; set; }
    }


 public class L_RedundancyField
    {
        public string SignatureOption { get; set; }
    }


 public class L_ProductInformations
    {
        public string Description { get; set; }
        public string Quantity { get; set; }
        public string Weights { get; set; }
        public string WeightUnits { get; set; }
        public string Currency { get; set; }
        public string Value { get; set; }
        public string Sku { get; set; }
        public string Remark { get; set; }
        public string ProductUrl { get; set; }
        public string HSCode { get; set; }
    }

 

 類定義完成之后定義一個api控制器:(由於我的數據是從數據庫中得到的,所以會有 GetLable(); GetParcelInformation(); GetProductInformations(); GetRecipientAddress(); GetRedundancyField(); GetData(); 方法去查詢數據查詢的方法自行定義

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Tally_test.Model;
using Newtonsoft.Json;
using System.Data;
using System.Text;
using System.Net;
using System.IO;

namespace Tally_test.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private IVLableListService _VLableList { get; set; }
        public ValuesController(IVLableListService VLableList)
        {
            _VLableList = VLableList;
        }


        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }



        //查詢標簽數據
        public async Task<L_Lable> GetLable()
        {
            try
            {
                var x = _VLableList.GetLable();
                return await x;
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task<L_ParcelInformation> GetParcelInformation()
        {
            try
            {
                var x = _VLableList.GetParcelInformation();
                return await x;
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task<L_ProductInformations> GetProductInformations()
        {
            try
            {
                var x = _VLableList.GetProductInformations();
                return await x;
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task<L_RecipientAddress> GetRecipientAddress()
        {
            try
            {
                var x = _VLableList.GetRecipientAddress();
                return await x;
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task<L_RedundancyField> GetRedundancyField()
        {
            try
            {
                var x = _VLableList.GetRedundancyField();
                return await x;
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task<L_Data> GetData()
        {
            try
            {
                var x = _VLableList.GetData();
                return await x;
            }
            catch (Exception)
            {
                throw;
            }
        }
       

 控制器的主要內容我另起一標簽(標黃部分為給子級類賦值)注意賦值前后順序

[HttpGet("GetLables")]
        public string GetLables()
        {
            string result = "";           //接收從數據庫中查詢的數據
            var a = GetLable();
            var b = GetParcelInformation();
            var c = GetProductInformations();
            var d = GetRecipientAddress();
            var e = GetRedundancyField();
            var f = GetData();
            //實例化類並進行賦值
            L_ProductInformations ProductInformations = new L_ProductInformations();
            {
                ProductInformations.Description = c.Result.Description;
                ProductInformations.Quantity = c.Result.Quantity;
                ProductInformations.Weights = c.Result.Weights;
                ProductInformations.WeightUnits = c.Result.WeightUnits;
                ProductInformations.Currency = c.Result.Currency;
                ProductInformations.Value = c.Result.Value;
                ProductInformations.Sku = c.Result.Sku;
                ProductInformations.Remark = c.Result.Remark;
                ProductInformations.ProductUrl = c.Result.ProductUrl;
                ProductInformations.HSCode = c.Result.HSCode;
            }
            L_RecipientAddress RecipientAddress = new L_RecipientAddress();
            {
                RecipientAddress.FirstName = d.Result.FirstName;
                RecipientAddress.LastName = d.Result.LastName;
                RecipientAddress.Company = d.Result.Company;
                RecipientAddress.StreetAddress = d.Result.StreetAddress;
                RecipientAddress.StreetAddress2 = d.Result.StreetAddress2;
                RecipientAddress.StreetAddress3 = d.Result.StreetAddress3;
                RecipientAddress.City = d.Result.City;
                RecipientAddress.State = d.Result.State;
                RecipientAddress.ZIPCode = d.Result.ZIPCode;
                RecipientAddress.Country = d.Result.Country;
                RecipientAddress.PhoneNumber = d.Result.PhoneNumber;
                RecipientAddress.PhoneExtension = d.Result.PhoneExtension;
                RecipientAddress.Email = d.Result.Email;
                RecipientAddress.IsResidential = d.Result.IsResidential;
            }
            L_RedundancyField RedundancyField = new L_RedundancyField();
            {
                RedundancyField.SignatureOption = e.Result.SignatureOption;
            }
            L_ParcelInformation ParcelInformation = new L_ParcelInformation();
            {
                ParcelInformation.Weight = b.Result.Weight;
                ParcelInformation.WeightUnit = b.Result.WeightUnit;
                ParcelInformation.Length = b.Result.Length;
                ParcelInformation.Width = b.Result.Width;
                ParcelInformation.Height = b.Result.Height;
                ParcelInformation.SizeUnit = b.Result.SizeUnit;
                ParcelInformation.ExistDangerousGoods = b.Result.ExistDangerousGoods;
                ParcelInformation.ProductInformations = ProductInformations;
            }
            L_Data datas = new L_Data();
            {
                datas.OrderID = f.Result.OrderID;
                datas.ChannelName = f.Result.ChannelName;
                datas.Token = f.Result.Token;
                datas.ServiceTypeCode = f.Result.ServiceTypeCode;
                datas.WarehouseCode = f.Result.WarehouseCode;
                datas.LabelMarkText = f.Result.LabelMarkText;
                datas.OrderID = f.Result.OrderID;
                datas.ParcelInformation = ParcelInformation;
                datas.RecipientAddress = RecipientAddress;
                datas.RedundancyField = RedundancyField;
 
            }
            V_LableList LableList = new V_LableList();
            {
                LableList.Requestld = a.Result.Requestld;
                LableList.RequestTime = a.Result.RequestTime;
                LableList.Version = a.Result.Version;
                LableList.Data = datas;
            }            //類實例化並賦值之后進行  json序列化   (LableList是父類,所以我們最后只要實例化父類就可以了)
            string Datajson = JsonConvert.SerializeObject(LableList);
            //HttpWebRepuest接收
            string URL = "https://.../Api/LabelPrintService/PrintLabel";//你需要調用的接口路徑
            Encoding dataEncode = Encoding.UTF8;//編碼格式
            result = OpenReadWithHttps(URL, Datajson, dataEncode);
            return result;
        }
 
       //方法為了方便我就寫在了控制器里,盡量放到類里面
        public string OpenReadWithHttps(string URL, string paramData, Encoding dataEncode)
        {
            string responseContent = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //轉化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(URL));
                webReq.Method = "POST";
                webReq.ContentType = "application/json";
                webReq.ContentLength = byteArray.Length;
                //webReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes()));
                using (Stream reqStream = webReq.GetRequestStream())
                {
                    reqStream.Write(byteArray, 0, byteArray.Length);//寫入參數
                }
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
                {     /*這里面寫你需要進行的操作*/
                         /*
                           responseContent = sr.ReadToEnd().ToString();
                           string a = GetJsonValue(responseContent);
                           //主要進行byte[]類型轉換的
                            L_Data data = JsonConvert.DeserializeObject<L_Data>(a);
                                         System.IO.File.WriteAllBytes(@"D:\61290983244643354835.jpg", data.LabelImage);
                         */
        }
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
    return responseContent;
}
                public static string GetJsonValue(string strJson)
               {
                    string strResult;
                   JObject jo = JObject.Parse(strJson);
                   string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
                   if (values == null)
                   {
                     strResult = "";
                   }
                  else
                  { 
                     strResult = values[0];
                 }
                return strResult;
             }
    }
}

  

 現在我們來看一下文檔中的返回參數和效果

 

 

 再來看一下我們的運行效果

 

 

這個接口的主要作用是打印標簽,上面數據中的“LableImage”屬性的值是byte[]類型,需要我們自行處理為圖片類型就好了

 

 

以上僅為個人操作所得,有誤之處,敬請之出,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM