C# 发送HTTP请求 C#解析Json格式


之前做的一个项目当中要向网站发送请求,然后网站返回给我一个Json格式的数据,对Json格式数据进行处理

请求方法如下

public string GetPage(string requestUrl)
        {
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(requestUrl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET"; //请求方式GET或POST
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("Authorization", "Basic YWRtaW46YWRtaW4=");

                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页(html)代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                Log.LogError(ex);
                MessageBox.Show(ex.Message, "服务连接", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "";
            }
        }
View Code

参数requestUrl为请求的地址,返回为string类型
下面是示例演示,调用GetPage方法,返回的字符串格式是Json类型的,我这里把这个格式转换成了PersonChronicDisease这个对象以便在项目中使用

string response=GetPage(http://xxxx);
PersonChronicDisease pcd=JsonConvert.DeserializeObject(response, typeof(PersonChronicDisease)) as PersonChronicDisease;

JsonConvert在Newtonsoft.Json命名空间下,所以我们要添加Newtonsoft.Json.dll

大家有什么不懂的,可以在下面留言


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM