java调用百度统计api获取统计数据

管理员 8月前 ⋅ 867 阅读

 

大概流程

编写https请求工具类

package com.mtons.mblog.baiduapi;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpsUtil
{
    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // TODO Auto-generated method stub

        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // TODO Auto-generated method stub

        }

        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {

        public boolean verify(String arg0, SSLSession arg1) {
            // TODO Auto-generated method stub
            return false;
        }
    }

    /**
     * post方式请求服务器(https协议)
     *
     * @param url
     *            请求地址
     * @param content
     *            参数
     * @param charset
     *            编码
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     */
    public static byte[] post(String url, String content, String charset)
            throws NoSuchAlgorithmException, KeyManagementException,
            IOException {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
                new java.security.SecureRandom());

        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.setDoOutput(true);
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(content.getBytes(charset));
        // 刷新、关闭
        out.flush();
        out.close();
        InputStream is = conn.getInputStream();
        if (is != null) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            return outStream.toByteArray();
        }
        return null;
    }

}

 

获取siteid,请求地址https://api.baidu.com/json/tongji/v1/ReportService/getSiteList

import org.json.JSONObject;

public class TjApi {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            JSONObject header = new JSONObject();
            header.put("username", "");//用户名
            header.put("password", "!");//用户密码
            header.put("token", "");//申请到的token
            header.put("account_type", "1");

            String urlStr = "https://api.baidu.com/json/tongji/v1/ReportService/getSiteList";
            String charset = "utf-8";

            JSONObject params = new JSONObject();
            params.put("header", header);

            byte[] res = HttpsUtil.post(urlStr, params.toString(), charset);
            String s = new String(res);
            System.out.println(s);    
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

}

输出结果

 

{
    "header":{
        "desc":"success",
        "failures":[

        ],
        "oprs":1,
        "succ":1,
        "oprtime":0,
        "quota":1,
        "rquota":49992,
        "status":0
    },
    "body":{
        "data":[
            {
                "list":[
                    {
                        "status":0,
                        "create_time":"2017-04-26 17:25:10",
                        "domain":"tourforce.asia",
                        "site_id":10646729,
                        "sub_dir_list":[

                        ]
                    }
                ]
            }
        ]
    }
}​

 

找到我们需要用到的site_id

获取我们需要的统计数据,下图我获取的是昨日和今日的IP、PV和UV数据,请求地址https://api.baidu.com/json/tongji/v1/ReportService/getData

 

 

 

package com.mtons.mblog.baiduapi;

import com.google.gson.Gson;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.*;


public class TjApi {
    /**
     * header : {"desc":"success","failures":[],"oprs":1,"succ":1,"oprtime":0,"quota":1,"rquota":49958,"status":0}
     * body : {"data":[{"result":{"items":[[["2020/03/26"],["2020/03/27"]],[[1144,89,94],[612,78,79]],[],[]],"timeSpan":["2020/03/26 - 2020/03/27"],"fields":["simple_date_title","pv_count","visitor_count","ip_count"]}}]}
     */

    public static List getBaiduApiData(){
        try {
            JSONObject header = new JSONObject();
            header.put("username", "");//用户名
            header.put("password", "");//用户密码
            header.put("token", "");//申请到的token
            header.put("account_type", "1");
            //String urlStr = "https://api.baidu.com/json/tongji/v1/ReportService/getSiteList";

            String urlStr = "https://api.baidu.com/json/tongji/v1/ReportService/getData";
            String charset = "utf-8";

            JSONObject body = new JSONObject();
            body.put("siteId","14335607");
            body.put("method","overview/getTimeTrendRpt");//需要获取的数据



            Date d = new Date();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String dateNowStr = sdf.format(d);
            System.out.println("格式化后的日期:" + dateNowStr);

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(d);
            calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动
            String yesterday = sdf.format(calendar.getTime());


            body.put("start_date",yesterday);
            body.put("end_date",dateNowStr);
            body.put("metrics","pv_count,visitor_count,ip_count");//指标,数据单位

            JSONObject params = new JSONObject();
            params.put("header", header);
            params.put("body", body);

            byte[] res = HttpsUtil.post(urlStr, params.toString(), charset);
            String s = new String(res);

            Gson gson=new Gson();
            BaiduEntity baiduEntity=gson.fromJson(s,BaiduEntity.class);//s为返回的json,areaInfo为解析出来的实体类

            List list = baiduEntity.getBody().getData().get(0).getResult().getItems().get(1);
            return  list;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        getBaiduApiData();

    }


}

重点:数据解析

根据返回的数据格式新建一个实体类,在这里推荐一个idea的插件GsonFormat,简直不要太方便,安装好后重启idea

点击左下角setting,直接点击ok生成实体类即可,最后解析成实体类就可以取值啦

Gson gson=new Gson();
 BaiduEntity baiduEntity=gson.fromJson(s,BaiduEntity.class);//s为返回的json,areaInfo为解析出来的实体类

 

我有话说:

全部评论: 0