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

}


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