c#导入百度统计API数据

最近项目中需要增加一些新功能:当前在线人数,总访问量统计,今日访问量,上一年度访问量,找了很多第三方统计工具,最后确定用百度统计,因为项目是vue的,直接引入的时候出现了跨域,发现前端用jsonp解决不了,所以就直接用c#请求再返回给前端了,话不多说,具体操作如下(本人最近新学c#,欢迎大佬指正)

首先去百度统计官网注册登录站长号,然后在需要统计的网站加入代码,获得token,这些不多说

AjaxResult result = new AjaxResult();
            var endDate = DateTime.Now.ToString("yyyyMMdd");
            var laststartDate = DateTime.Now.Year - 1 + "0101";
            var LastendDate = DateTime.Now.Year - 1 + "1231";
            string url = "https://api.baidu.com/json/tongji/v1/ReportService/getData";
            var header = new
            {
                account_type = 1,
                username = "百度统计站长用户名",         
                password = "百度统计站长密码",         
                token = "token"      
            };
            var bodya = new
            {
                site_id = "网站id",           
                start_date = "20200528",        //是5.28加的百度统计代码,所以从5.28开始计算
                end_date = endDate,
                metrics = "pv_count,visitor_count",
                method = "source/all/a",     //总访问量
                tab = "visit"
            };
            var bodyb = new
            {
                site_id = "网站id",
                start_date = "",
                end_date = endDate,
                metrics = "pv_count,visitor_count",
                method = "source/all/a",     //当日访问量
                tab = "visit"
            };
            var bodyc = new
            {
                site_id = "网站id",
                start_date = laststartDate,
                end_date = LastendDate,
                //start_date = "20200101",
                //end_date ="20201231",
                metrics = "",
                method = "source/all/a",     //上一年度访问量
                tab = "visit"
            };
            var bodyd = new
            {
                site_id = "网站id",
                start_date = "",
                end_date = "",
                metrics = "",
                method = "/trend/latest/f",     //当日在线人数
                tab = "visit"
            };
            Object[] bodyList = new Object[4] { bodya, bodyb, bodyc, bodyd }; //我这里是想一次将需要的四条数据              都返回,所以就写了个数组,将四组数据放里面,以循环的方式进行四次请求
            int count = 0,currentDay=0,currentLast=0, onlineNumber=0;   //定义四个变量,分别在后面接收需要的四个数据
//循环请求百度的接口
             for (int i = 0; i < bodyList.Length; i++)
                {
                    var body = bodyList[i];
                    var postData = new { header, body };
                    string jResult = JsonConvert.SerializeObject(postData);
                    AjaxResult ajaxresult = new AjaxResult();
                    HttpClient httpClient = new HttpClient();
                    UTF8Encoding encoding = new UTF8Encoding();
                    byte[] byte1 = encoding.GetBytes(jResult);
                    var content = new ByteArrayContent(byte1);
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
                    var response = httpClient.PostAsync(url, content).Result;
                    string results = response.Content.ReadAsStringAsync().Result;
                    //因为返回的数据格式不一样(统计访问量和获取当前在线的不一样)所以需要先定义两组不同的数据类型
                    }


定义类型


获取访问量的
 public class BaiduModel
    {
        public BaiduBody Body { get; set; }
    }
    public class BaiduBody
    {
        public List<BaiduListItem> Data { get; set; }
    }

    public class BaiduListItem
    {
        public BaiduResult Result { get; set; }
        
    }

    public class BaiduResult
    {
        public List<List<string>> Sum { get; set; }
    }

获取当前在线人数
 public class BaiduModela
    {
        public BaiduBodya Body { get; set; }
    }
    public class BaiduBodya
    {
        public List<BaiduListItema> Data { get; set; }
    }

    public class BaiduListItema
    {
        public BaiduResulta Result { get; set; }

    }
    public class BaiduResulta
    {
        public int OnlineNumber { get; set; }
    }

}

将返回来的数据转换成自己需要的

var model = JsonConvert.DeserializeObject<BaiduModel>(results);
                    if (model.Body.Data[0].Result.Sum != null)
                        if (i == 0)
                        {
                            List<List<string>> sumList = model.Body.Data[0].Result.Sum;
                            List<string> sumNumAll = sumList[0];

                            if (sumNumAll[0] == "--")
                            {
                                count = 0;
                            }
                            else
                            {
                                count = int.Parse(sumNumAll[0]);
                            }
                        };
                    if (i == 1)
                    {
                        List<List<string>> sumList = model.Body.Data[0].Result.Sum;
                        List<string> sumNumAll = sumList[0];

                        if (sumNumAll[0] == "--")
                        {
                            currentDay = 0;
                        }
                        else
                        {
                            currentDay = int.Parse(sumNumAll[0]);
                        }
                    };
                    if (i == 2)
                    {
                        List<List<string>> sumList = model.Body.Data[0].Result.Sum;
                        List<string> sumNumAll = sumList[0];
                        if (sumNumAll[0] == "--")
                        {
                            currentLast = 0;
                        }
                        else
                        {
                            currentLast = int.Parse(sumNumAll[0]);
                        }

                    };
                    if (i == 3)
                    {
                        var modela = JsonConvert.DeserializeObject<BaiduModela>(results);
                        int OnlineNum = modela.Body.Data[0].Result.OnlineNumber;
                        onlineNumber = OnlineNum;
                    };
                }
                result.Data = new
                {
                    Count = count,
                    CurrentDay = currentDay,
                    CurrentLast = currentLast,
                    OnlineNumber = onlineNumber
                };

最后附完整代码

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using Samson.Business;
using Samson.Model.Entity;
using Samson.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace Samson.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BaiduApiController : ControllerBase
    {
        [HttpGet]
        public JsonResult GetAllSum()
        {
            AjaxResult result = new AjaxResult();
            var endDate = DateTime.Now.ToString("yyyyMMdd");
            var laststartDate = DateTime.Now.Year - 1 + "0101";
            var LastendDate = DateTime.Now.Year - 1 + "1231";
            string url = "https://api.baidu.com/json/tongji/v1/ReportService/getData";
            var header = new
            {
                account_type = 1,
                username = "",         //百度统计站长用户名
                password = "",         //百度统计站长密码
                token = ""      //token
            };
            var bodya = new
            {
                site_id = "",           //网站id
                start_date = "20200528",        //是5.28加的百度统计代码,所以从5.28开始计算
                end_date = endDate,
                metrics = "pv_count,visitor_count",
                method = "source/all/a",     //总访问量
                tab = "visit"
            };
            var bodyb = new
            {
                site_id = "",
                start_date = "",
                end_date = endDate,
                metrics = "pv_count,visitor_count",
                method = "source/all/a",     //当日访问量
                tab = "visit"
            };
            var bodyc = new
            {
                site_id = "",
                start_date = laststartDate,
                end_date = LastendDate,
                //start_date = "20200101",
                //end_date ="20201231",
                metrics = "",
                method = "source/all/a",     //上一年度访问量
                tab = "visit"
            };
            var bodyd = new
            {
                site_id = "",
                start_date = "",
                end_date = "",
                metrics = "",
                method = "/trend/latest/f",     //当日在线人数
                tab = "visit"
            };

            Object[] bodyList = new Object[4] { bodya, bodyb, bodyc, bodyd };
            int count = 0,currentDay=0,currentLast=0, onlineNumber=0;
                for (int i = 0; i < bodyList.Length; i++)
                {
                    var body = bodyList[i];
                    var postData = new { header, body };
                    string jResult = JsonConvert.SerializeObject(postData);
                    AjaxResult ajaxresult = new AjaxResult();
                    HttpClient httpClient = new HttpClient();
                    UTF8Encoding encoding = new UTF8Encoding();
                    byte[] byte1 = encoding.GetBytes(jResult);
                    var content = new ByteArrayContent(byte1);
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
                    var response = httpClient.PostAsync(url, content).Result;
                    string results = response.Content.ReadAsStringAsync().Result;
                    var model = JsonConvert.DeserializeObject<BaiduModel>(results);
                    if (model.Body.Data[0].Result.Sum != null)
                        if (i == 0)
                        {
                            List<List<string>> sumList = model.Body.Data[0].Result.Sum;
                            List<string> sumNumAll = sumList[0];

                            if (sumNumAll[0] == "--")
                            {
                                count = 0;
                            }
                            else
                            {
                                count = int.Parse(sumNumAll[0]);
                            }
                        };
                    if (i == 1)
                    {
                        List<List<string>> sumList = model.Body.Data[0].Result.Sum;
                        List<string> sumNumAll = sumList[0];

                        if (sumNumAll[0] == "--")
                        {
                            currentDay = 0;
                        }
                        else
                        {
                            currentDay = int.Parse(sumNumAll[0]);
                        }
                    };
                    if (i == 2)
                    {
                        List<List<string>> sumList = model.Body.Data[0].Result.Sum;
                        List<string> sumNumAll = sumList[0];
                        if (sumNumAll[0] == "--")
                        {
                            currentLast = 0;
                        }
                        else
                        {
                            currentLast = int.Parse(sumNumAll[0]);
                        }

                    };
                    if (i == 3)
                    {
                        var modela = JsonConvert.DeserializeObject<BaiduModela>(results);
                        int OnlineNum = modela.Body.Data[0].Result.OnlineNumber;
                        onlineNumber = OnlineNum;
                    };
                }
                result.Data = new
                {
                    Count = count,
                    CurrentDay = currentDay,
                    CurrentLast = currentLast,
                    OnlineNumber = onlineNumber
                };
                result.IsSuccess = true;
                result.Message = "操作成功";
            //  Newtonsoft.Json.Linq.JObject resultObject = Newtonsoft.Json.Linq.JObject.Parse(results);
            return new JsonResult(result);
        }
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章