剛學C#, 折騰的一個小玩意. 熟悉和了解C#這門編程語言. 沒有啥特殊意義編程
解鎖技能
- System.Net 的 WebRequest等http請求
- Newtonsoft.Json 這個第三方類庫, 序列號與反序列號JSONjson
第三方類庫到」工具->NuGet包管理->管理解決方案包…」 查詢」JSON.NET」app
解鎖技能 「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].姓名」); 這樣. (可能其餘庫支持)post
天天進步一點點url