刚学C#, 折腾的一个小玩意. 熟悉和了解C#这门编程语言. 没有啥特殊意义
解锁技能
- System.Net 的 WebRequest等http请求
- Newtonsoft.Json 这个第三方类库, 序列号与反序列号JSON
第三方类库到”工具->NuGet包管理->管理解决方案包…” 查询”JSON.NET”
解锁技能 “vs死丢丢解决方案包管理”
using System;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace Kuaidi100
{
public class JsonAutoComNum_Auto
{
//{"comCode":"rufengda","id":"","noCount":276344,"noPre":"117082","startTime":""}
public string comCode, noPre, startTime, id;
public int noCount;
}
public class JsonAutoComNum
{
//{"comCode":"","num":"117082212900994501","auto":[{"comCode":"dhl","id":"","noCount":1,"noPre":"117082","startTime":""}]}
public string comCode;
public string num;
public JsonAutoComNum_Auto[] auto = new JsonAutoComNum_Auto[0];
}
public class JsonQuery
{
//{"message":"ok","nu":"117082212900994501","ischeck":"1","condition":"F00","com":"rufengda","status":"200","state":"3", "data":[]}
public string message, nu, ischeck, condition, com, status, state;
public JsonQuery_Data[] data = new JsonQuery_Data[0];
}
public class JsonQuery_Data
{
//{"time":"2017-08-23 13:34:21","ftime":"2017-08-23 13:34:21","context":"运单已送达成功 ","location":""}
public string time, ftime, context, location;
}
class Program
{
static void Main(string[] args)
{
string nu = "117082212900994501";//运单编号
//创建请求
WebRequest get = WebRequest.Create("http://www.kuaidi100.com/autonumber/autoComNum?text=" + nu);
get.Method = "get";
//发送并取回响应内容
WebResponse response = get.GetResponse();
string responseStr = new StreamReader(response.GetResponseStream()).ReadToEnd(); //结果转换到string
response.Close();
//json字符串解析为对象
JsonAutoComNum json = JsonConvert.DeserializeObject<JsonAutoComNum>(responseStr);
Console.WriteLine(responseStr);
string type = json.comCode == "" ? json.auto[0].comCode : json.comCode;//自动判定快递公司代码没有, 从可能是快递公司列表中选取[0]
WebRequest post = WebRequest.Create("http://www.kuaidi100.com/query");
//组合参数
string postData = string.Format("type={0}&postid={1}&id={2}&valicode={3}&temp={4}", type, nu, "1", "", "0.396747639110379");
byte[] data = Encoding.ASCII.GetBytes(postData);
//协议头/参数等
post.Method = "post";
post.ContentType = "application/x-www-form-urlencoded";
post.ContentLength = data.Length;
post.GetRequestStream().Write(data, 0, data.Length);
response = post.GetResponse();
responseStr = new StreamReader(response.GetResponseStream()).ReadToEnd(); //结果转换到string
//结果字符串转换为JsonQuery对象
JsonQuery query = JsonConvert.DeserializeObject<JsonQuery>(responseStr);
//格式输出
Console.WriteLine(string.Format("查询结果:{0}\n运单编号:{1}\n快递公司:{2}\n快递状态:{3}", query.message, query.nu, query.com, query.state));
for (int i = 0; i < query.data.Length; i++)
{
Console.WriteLine(string.Format("{0} --- {1}", query.data[i].time, query.data[i].context));
}
Console.ReadKey();
}
}
}
没想到vs死丢丢内置一个类库市场(NuGet包管理器), 很方便. 一开始我以为第三方类库都要一个一个去百度下载…
另外一个就是, 目前就用过Newtonsoft.Json这个JSON类库. 原来还需要声明一个用做映射json的类. 不能像js那样直接访问对象(这个对象需要自己创造, 然后映射绑定字段). 或者直接用方法获取 json.getValue(“成员[0].姓名”); 这样. (可能其他库支持)
每天进步一点点
手机扫一扫
移动阅读更方便
你可能感兴趣的文章