码迷,mamicode.com
首页 > Windows程序 > 详细

C#如何拿到从http上返回JSON数据?

时间:2017-09-19 22:50:43      阅读:5469      评论:0      收藏:0      [点我收藏+]

标签:mod   app   pos   tar   运行   12px   keepalive   cti   创建   

在实际开发中,我们经常会使用到API,所谓API一般就是一个地址,我们称之为接口。然后我们通过用C#对这地址发送请求,请求后,服务器就会给我们返回数据,一般是XML或者JSON,这里我们主要讲述的是JSON。

为了演示,我们这里准备了一个接口,这是一个查询物流的接口。(读者读到这篇文章的时候,接口可能有效,也可能失效,因为接口是网上找的,不是笔者自己写的,但是原理是一样的。)

接口:  http://www.kuaidi100.com/query?type=快递公司编码&postid=物流单号

(ps:快递公司编码:申通="shentong" EMS="ems" 顺丰="shunfeng" 圆通="yuantong" 中通="zhongtong" 韵达="yunda" 天天="tiantian" 汇通="huitongkuaidi" 全峰="quanfengkuaidi" 德邦="debangwuliu" 宅急送="zhaijisong")

一般我们拿到接口后,需要拼接成我们需要的地址。比如,我们现在需要查询顺丰物流367847964498单的结果。那么,我们就需要拼接这个接口,拼接结果如下:

http://www.kuaidi100.com/query?type=shunfeng&postid=367847964498

我们拼接好后,可以直接在浏览器上访问这个地址,看看是不是可以正常访问。如果可以正常访问,说明我们这个接口没有问题。那么,我们现在先在浏览器访问一下。看到下面返回的结果就说明正确。

技术分享

接下来就是大家最喜欢的写代码环节,为了方便演示,我们这里用winform程序。非常简单,我们新建一个窗体程序,点击后,弹出JSON数据即可。界面如下:

技术分享

建好窗体,放一个按钮,然后我们来创建一个类HttpUitls。这个是这个文章中最重要的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WindowsFormsApplication1
{
    public class HttpUitls
    {
         public static string Get(string Url)
        {
            //System.GC.Collect();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }

            return retString;
        }

        public static string Post(string Url, string Data, string Referer)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.Referer = Referer;
            byte[] bytes = Encoding.UTF8.GetBytes(Data);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            Stream myResponseStream = request.GetRequestStream();
            myResponseStream.Write(bytes, 0, bytes.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            return retString;
        }
    
    }
}

这个类有两个方法,一个是Get,一个是Post,本篇文章我们只需要用到Get就可以了。

然后是点击按钮的方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //我们的接口
            string url = "http://www.kuaidi100.com/query?type=shunfeng&postid=367847964498";

            //将接口传入,这个HttpUitls的类,有兴趣可以研究下,也可以直接用就可以,不用管如何实现。
            string getJson = HttpUitls.Get(url);

            MessageBox.Show(getJson);
        }
    }
}

 

 然后是运行结果

技术分享

到这一步说明我们已经成功拿到接口给我们返回的JSON数据了。那么我们会在下一篇文章中讲解如何使用这JSON数据,也就是解析JSON

 

C#如何拿到从http上返回JSON数据?

标签:mod   app   pos   tar   运行   12px   keepalive   cti   创建   

原文地址:http://www.cnblogs.com/linfenghp/p/7554113.html

(0)
(2)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!