C# WinForm 模擬HTTP請求,並解析

使用的是 Newtonsoft.Json.dll 請自行下載並引入,下面的簡單的源碼均來自網上。

using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

        static void Main()
        {

            String jsonStr = HttpPost("http://localhost:81/Api/ErpShopClient.asp?Act=Login", "eId=99999&shopId=2&token=123", false);
            Console.WriteLine(jsonStr);

            JObject json = JObject.Parse(jsonStr);
            Console.WriteLine(json.Count);
            Console.WriteLine("success:" + json.SelectToken("success") + " message:" + json.Property("message"));

            //遍歷
            String tempStr = "{\"configs\": {\"index\": 0,\"list\": [{\"server\": \"\",\"app_key\": \"45c6af3c98409b18a84451215d0bdd6e\",\"roomlistserver\": \"http://app.netease.im/api/chatroom/homeList\"}]},\"abc\":123}";
            JObject jsonJbo = JObject.Parse(tempStr);
            foreach (var item in jsonJbo)
            {
                String key = item.Key;
                var val = item.Value;
                Console.WriteLine(key + ":" + val + " type=" + val.GetType());
            }

            Console.ReadKey();
        }

        private static string HttpPost(string Url, string postDataStr, bool submitType)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            if (submitType)
                request.ContentType = "application/json";
            else
                request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章