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;
        }

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页