C#从http上返回JSON数据

一:C#从http上取JSON数据
向服务器请求数据后,一般时XML或JSON:(以JSON为例)
在C#中WinForm为例操作:
Util工具类:

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

namespace WindowsUtil
{
    public class HttpUitls
    {
         public static string GetHtml(string Url)
        {
        	//可以看看request属性,取所需要的内容,这里参数可以改为实体类,向方法传参
        	//还额外有个cookie字段很重要!!!
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);//请求地址
            request.Method = "GET";//请求方法
            request.AllowAutoRedirect = true;//重定向
            request.Proxy = null;//代理信息
            request.KeepAlive = false;
            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;
        }  
    }
}

窗体中点击发生事件:

private string searchUrl = $"http://www.chinamoney.com.cn/ags/ms/cm-u-bk-fx/RefRateHis?lang=cn&";

private void Btnsearch_Click(object sender, EventArgs e)
{
	try
	{
		DateTime dateTime = Convert.ToDateTime(this.Datepick.Month);
		string hbxz = "ALL";
		if (!string.IsNullOrEmpty(this.Ddlhbxz.SelectedValue))
		{
		    hbxz = this.Ddlhbxz.SelectedValue;
		}
		string Url = searchUrl + "startDateTool=" + DateHelper.GetCurMonthFirstDay(dateTime) + "&" + "endDateTool=" + DateHelper.GetCurMonthLastDay(dateTime) + "&currencyCode=" + hbxz;
		var result = PostHelper.Get(Url);
		var rootobject= JsonConvert.DeserializeObject<Rootobject> (result);
		///
		//处理获取到的信息源
		///
	}
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }   
}              

二:公司中已经封好的方法使用:
第一步:先添加引用;
Universal.Kits
第二步:书写方法;

private string get(string url)
{
    var result = new HttpHelper().GetHtml(new HttpItem
    {
        URL = url,//请求地址
        Method="get",//方法
        Allowautoredirect=true//重定向
    }) ;
    if (result.StatusCode == System.Net.HttpStatusCode.OK)
    {
        return result.Html;
    }
    return null;       
}

第三步:调用方法获取数据;
第四步:转为获取到的数据源实体类;
注:Rootobject是封好的实体类。
result是上述方法的返回字符串。

var rootobject= JsonConvert.DeserializeObject<Rootobject> (result);

三:http获取网页界面所显示数据
第一步:封好的方法:

public static string HttpGet(string url)
{
    //cookie是要在网页F12看到的cookie “复制过来”
    string cookiestr = "cookies";
    //创建请求
    HttpWebRequest httpWebRequest=(HttpWebRequest)WebRequest.Create(url);
    //请求方式
    httpWebRequest.Method = "GET";
    //设置请求超时时间
    httpWebRequest.Timeout = 10000;
    //设置cookie
    httpWebRequest.Headers.Add("Cookie", cookiestr);
    //发送请求
    HttpWebResponse httpWebResponse=(HttpWebResponse)httpWebRequest.GetResponse();
    //利用Stream流读取返回数据
    StreamReader streamReader=new StreamReader(httpWebResponse.GetResponseStream());
    //获得最终数据,一般是JSON
    string responseContent=streamReader.ReadToEnd();
    streamReader.Close();
    httpWebResponse.Close();

    //返回到的一般是JSON格式的字符串
    return responseContent;
}

第二步:调用方法

 string txt = HttpGet(@"url");
 HtmlDocument doc = new HtmlDocument();
 doc.LoadHtml(txt);
 var div = doc.DocumentNode.SelectNodes("//div[@id='all-list']//ul//li//a[@class='title']");//div的ID class找到具体位置
 foreach (HtmlNode node in div)
 {
     string href = node.GetAttributeValue("href", "");
     Console.WriteLine(string.Format("{0}-----------{1}",
     node.InnerText,
     node.GetAttributeValue("href", "")+"\r\n"));
 }
 Console.ReadKey();

关于网页信息内容学习总结和心得…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值