**公司需要调用百度统计的api,昨天搞了一天,先看了百度统计的官方文档 emmmmmmm 是真的没怎么看懂,然后在网上搜了各位大牛的实现,最后自己尝试了一下访问成功!**
思路大概是这样的
1、先写一个能调用https的 java类
2、调用 https://api.baidu.com/json/tongji/v1/ReportService/getSiteList 接口获得siteId的列表
3、调用 https://api.baidu.com/json/tongji/v1/ReportService/getData 获得你需要的统计数据
首先是访问https的类(网上找大牛copy的):
类名 HttpsUtil
package com.cutc.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的方法:
package com.cutc.baiduapi;
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
然后再去请求这个site_id的数据:
package com.cutc.baiduapi;
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 urlStr = "https://api.baidu.com/json/tongji/v1/ReportService/getData";
String charset = "utf-8";
JSONObject body = new JSONObject();
body.put("siteId","10646729");
body.put("method","overview/getTimeTrendRpt");//需要获取的数据
body.put("start_date","20171220");
body.put("end_date","20171222");
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);
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":49989,
"status":0
},
"body":{
"data":[
{
"result":{
"items":[
[
[
"2017/12/20"
],
[
"2017/12/21"
],
[
"2017/12/22"
]
],
[
[
17694,
8811,
8450
],
[
17271,
8435,
7996
],
[
17169,
8306,
8029
]
],
[
],
[
]
],
"timeSpan":[
"2017/12/20 - 2017/12/22"
],
"fields":[
"simple_date_title",
"pv_count",
"visitor_count",
"ip_count"
]
}
}
]
}
}
这样就获取到了PV,UV,IP
最后说一下body中method参数和metrics参数,这两个参数官方文档中有这里是链接:
http://tongji.baidu.com/open/api/more?p=tongjiapi_getData.tpl
嘛~希望能帮助到刚刚接触百度统计的朋友!