Api程序接口对接

时间:2022-07-03 13:08:51

先看一下参数表和参数示例

Api程序接口对接

 

Api程序接口对接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;
             }
    }
}

  

 现在我们来看一下文档中的返回参数和效果

Api程序接口对接 

 

 再来看一下我们的运行效果

Api程序接口对接

 

 

这个接口的主要作用是打印标签,上面数据中的“LableImage”属性的值是byte[]类型,需要我们自行处理为图片类型就好了

 

 

以上仅为个人操作所得,有误之处,敬请之出,谢谢。