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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值