C# 接口请求返回值的几种实现方式(最详细)

第一种:
定义一个字典,存储字段值:

Dictionary  dic = new Dictionary();

根据需求文档的值,将相关字段存入字典:

                dic.Add("rdcId", config.kxApp_key);
                dic.Add("barcode", barcode);
                dic.Add("action", "INLAND_OPT_WEIGH_VOLUME");
                dic.Add("checkWeight", (Weight * 1000).ToString());
                dic.Add("deviceId", config.ClientId);             

序列化,序列化前面一定要定义var或者object类型,别问我为什么强调:

  var data_message = JsonConvert.SerializeObject(dic);

发送请求,获取返回值,这里是封装好了的ajax请求,不会的百度,调用一下就行了:

 var result = HttpHelper.GetResponseString(HttpHelper.CreatePostHttpResponse(url, dic, 0, null));              

反序列化:

  var les = JsonHelper.JSONToObject(result);//ResultCode:封装的返回值

判断

if(les.success==true){
Console.Weite(“成功!”);
}
else{
Console.Weite(“失败!”);
}

提前封装好的返回值:

  public class ResultCode
        {
            /// 
            /// 是否成功
            /// 
            public bool success { get; set; }
            /// 
            /// 成功,100
            /// 报文错误,200
              /// 
            public string code { get; set; }
        }

第二种与第一种,就前面部分不一样,不用存入字典,直接:

var data = new
                {
                    rdcId = config.kxApp_key,
                    barcode = code,
                    action = "INLAND_OPT_WEIGH_VOLUME",
                    checkWeight = weight * 1000,
                    checkLength = (int)length,
                    checkWidth = (int)width,
                    checkHeight =(int) height,
                    checkVolume = (int)(volume/1000),
                    carlabel = config.CarLabel,
                    deviceId = config.ClientId,
                    version = "1.0.0",
                    timestamp = long.Parse(timestamp),
                    decryptType = "MD5"
                };

然后序列化,发送请求,获取返回值,反序列化,判断即可。

你可能感兴趣的:(MVC,winform窗体,.NET,Web)