博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Api程序接口对接
阅读量:6236 次
发布时间:2019-06-22

本文共 11849 字,大约阅读时间需要 39 分钟。

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

 

首先是参数,我们而已发现,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
> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult
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
GetLable() { try { var x = _VLableList.GetLable(); return await x; } catch (Exception) { throw; } } public async Task
GetParcelInformation() { try { var x = _VLableList.GetParcelInformation(); return await x; } catch (Exception) { throw; } } public async Task
GetProductInformations() { try { var x = _VLableList.GetProductInformations(); return await x; } catch (Exception) { throw; } } public async Task
GetRecipientAddress() { try { var x = _VLableList.GetRecipientAddress(); return await x; } catch (Exception) { throw; } } public async Task
GetRedundancyField() { try { var x = _VLableList.GetRedundancyField(); return await x; } catch (Exception) { throw; } } public async Task
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
(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[]类型,需要我们自行处理为图片类型就好了

 

 

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

转载于:https://www.cnblogs.com/A-R-E-S/p/11010740.html

你可能感兴趣的文章
权限组件(13):批量操作权限页面的展示和增删改查
查看>>
TP设置404页面
查看>>
Unhandled event loop exception 解决办法
查看>>
前端基础之HTML
查看>>
[前端JS学习笔记]JavaScript 数组
查看>>
Express框架学习总结
查看>>
UI组件-UISegmentedControl
查看>>
iOS 沙盒目录结构及正确使用
查看>>
课堂笔记
查看>>
后端技术体系框架
查看>>
下面这段java的源代码的意思
查看>>
Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
查看>>
摄像头驱动OV7725学习笔记连载(一):OV7725 电器特性和时序图
查看>>
IIS Express允许外部访问(外部调试)
查看>>
NSSet NSMutableSet的简单使用
查看>>
洛谷P1085不高兴的津津
查看>>
所有的企业都拥抱了互联网,云才有价值,用云计算的本质是用互联网。互联网企业需要满足两个特征,一是要有云计算,二是要在云计算的基础上用数据来优化业务。...
查看>>
阿里金融成立,从第一天开始,就使用阿里云的云计算平台作为运算淘宝和支付宝数据的计算后台。阿里小贷不需要抵押,纯信用贷款,目前已经能做到3分钟提交申请,1秒批准,0人工干预。数据成为新的信用。...
查看>>
0和1:裂变时刻-2.数据爆炸
查看>>
Python 核心编程(第二版)——模块
查看>>