美文网首页
百度推广统计对接

百度推广统计对接

作者: YAOAORAN | 来源:发表于2019-04-15 15:30 被阅读0次

以下所有内容引用自CSDN:shanhanyu(侵删)

百度推广官方文档地址

百度推广-登录接口

  1. 注册百度统计账户,确保网站昨日PV大于100,开通数据导出服务获得Token;

  2. 设置公钥key(随机生成),并进行RSA工具类获取公钥;

  3. 按照文档要求构造请求参数对象req(DoLoginRequestImpl);

  4. 将请求参数转换为JSON,并使用Gzip进行压缩;(消息头规范)

  5. 通过RSA工具类用公钥加密数据;(消息头规范)

  6. 通过HTTP请求进行登录,返回结果数据;

  7. 解压返回结果,获取UCID;

百度推广-获取站点列表

  1. 通过登录接口获取UCID;

  2. 调用获取站点列表接口;

  3. 解析响应结果,获取站点对应的siteId,具体响应内容见官方文档;

百度推广-获取站点访问数据

  1. 通过登录接口和获取站点列表接口得到UCID和SiteId;

  2. 拼接参数, 调用数据导出接口;

  3. 解析响应结果,具体响应内容见官方文档;

示例代码

实体(忽略getter/setter方法)
public class WebsiteUser implements Serializable {

    private String password;

    private String userName;

    private String token;

    private String ucid;

}
登录接口
    /**
     * 登陆接口
     * 将登陆用户信息进行压缩加密,然后登陆
     */
    public static DoLoginResponse doLogin(WebsiteUser site) {
        try {
            DoLoginRequestImpl req = new DoLoginRequestImpl();
            req.setPassword(site.getPassword());
            req.setUsername(site.getUserName());
            req.setUuid(AppConstans.UUID);
            req.setToken(site.getToken());
            req.setFunctionName(AppConstans.LOGIN_METHOD);
             //挂接方需要首先将消息转换成 JSON 格式,编码采用 UTF8,然后用 GZIP 对消息 JSON 进行压缩。压缩完毕后,采用 RSA 算法的公钥进行加密。
            Key publicKey = RSAUtil.getPublicKey(AppConstans.KEY);
            Gson gson = new Gson();
            String json = gson.toJson(req);
            byte[] bytes = RSAUtil.encryptByPublicKey(GZipUtil.gzipString(json), publicKey);
            String loginResult =  HttpClientUtils.doHttpPost(AppConstans.HOME_LOGIN_ADDRESS, bytes, 10000, "utf-8");
            DoLoginResponse resp = gson.fromJson(loginResult, DoLoginResponse.class);
            return resp;
            
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return null;
    }

HTTP请求封装

    /**
     * 仅用于登陆的http post请求
     * @param url
     * @param bytes
     * @param timeout
     * @param encode
     * @return
     */
    public static String doHttpPost(String url, byte[] bytes, int timeout, String encode){
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager());
        httpClient.getParams().setContentCharset(encode);
        PostMethod postMethod = new PostMethod(url);
        InputStream inputStream = new ByteArrayInputStream(bytes, 0, bytes.length);
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, bytes.length, "text/json; charset=utf-8");
        postMethod.setRequestEntity(requestEntity);
        postMethod.addRequestHeader("Content-Type", "text/json; charset=utf-8");
          postMethod.addRequestHeader("uuid", AppConstans.UUID);
         postMethod.addRequestHeader("account_type", "1");        //默认是百度账号
        try {
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
            
            int num = httpClient.executeMethod(postMethod);
            if (num == AppConstans.SC_OK) {
                InputStream in = postMethod.getResponseBodyAsStream();
                try {
                    byte[] b = new byte[8];
                    if (in.read(b) != 8) {
                        throw new ClientInternalException("Server response is invalid.");
                    }
                    if (b[1] != 0) {
                        throw new ClientInternalException("Server returned an error code: " + b[0]+b[1]+b[2]+b[3]+b[4]+b[5]+b[6]+b[7]);
                    }
                    int total = 0, k = 0;
                    b = new byte[AppConstans.MAX_MSG_SIZE];
                    while (total < AppConstans.MAX_MSG_SIZE) {
                        k = in.read(b, total, AppConstans.MAX_MSG_SIZE - total);
                        if (k < 0)
                            break;
                        total += k;
                    }
                    if (total == AppConstans.MAX_MSG_SIZE) {
                        throw new ClientInternalException("Server returned message too large.");
                    }
                    byte[] zip = ArrayUtils.subarray(b, 0, total);
                    zip = GZipUtil.unGzip(zip);
                    return new String(zip, "UTF-8");
                } catch (IOException e) {
                    throw new ClientInternalException(e);
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            throw new ClientInternalException(e);
                        }
                    }
                }
            }
        } catch (Exception e) {
        } finally {
            postMethod.releaseConnection();
        }
        return "";
    }
获取站点列表
    /**
     * 获取当前用户下的站点列表
     * @param user
     * @return
     */
    public static List getSiteList(WebsiteUser user){
        Gson gson = new Gson();
        AuthHeader header = new AuthHeader();
        header.setUsername(user.getUserName());
        header.setToken(user.getToken());
        header.setPassword(user.getPassword());
        header.setAccount_type(1);
        
        ApiRequest request = new ApiRequest();
        request.setHeader(header);
        String json = gson.toJson(request);
        String result =  HttpClientUtils.doPost(user.getUcid(),AppConstans.GET_SITE_LIST, json.getBytes(), 15000, "utf-8");
        ApiResponse resp = gson.fromJson(result, new TypeToken(){}.getType());
        //目前百度返回的信息结构为 body/data/list[],但是api文档中说明data下仅有一个list,所以只需要返回一个第一个list中集合即可
        if(null != resp && null != resp.getHeader() && null != resp.getHeader().getSucc() && resp.getHeader().getSucc()>0){
            return resp.getBody().getData().get(0).getList();
        }
        return null;
        }
获取访问数据接口
    /**
     * 查询站点数据
     * @param user      用户
     * @param siteId    站点ID
     * @param startDate 开始时间
     * @param endDate   结束时间
     */
    public static DataResult getSiteData(WebsiteUser user,Integer siteId,String startDate,String endDate,String gran){
        Gson gson = new Gson();
        AuthHeader header = new AuthHeader();
        header.setUsername(user.getUserName());
        header.setToken(user.getToken());
        header.setPassword(user.getPassword());
        header.setAccount_type(1);
        
        ApiRequest request = new ApiRequest();
        GetDataParamBase body = new GetDataParamBase();
        body.setSite_id(siteId);
        body.setMetrics(AppConstans.METRICS);
        body.setMethod(AppConstans.METHOD_TIME);
        body.setMax_result(0);      //  默认查询全部
        body.setGran(gran);
        //body.setOrder("visitor_count,desc");
        //body.setStart_index(0);   //  默认不分页
        body.setStart_date(startDate);
        body.setEnd_date(endDate);
        request.setHeader(header);
        request.setBody(body);
        String json = gson.toJson(request);
        String resultStr =  HttpClientUtils.doPost(user.getUcid(),AppConstans.GET_SITE_DATA, json.getBytes(), 20000, "utf-8");
        System.out.println("data result ---siteId --:"+siteId+"startDate:"+startDate+"endDate:"+endDate+"--result:"+resultStr);
        
        ApiResponse resp = gson.fromJson(resultStr.replaceAll("\"--\"", "0"), new TypeToken(){}.getType());
        GetDataResponse respResult = resp.getBody().getData().get(0);
        DataResult result = respResult.getResult();
        if(null != resp && null != resp.getHeader() && resp.getHeader().getSucc()>0){
        
            //百度返回数据中items 包含四个list 其中第一个是时间列表  第二个是数据列表  第三 第四均为空
            List itemDate = (List) resp.getBody().getData().get(0).getResult().getItems().get(0);
            List itemData = (List) resp.getBody().getData().get(0).getResult().getItems().get(1);
            
            List listResult = new ArrayList();
            DateCount dc;
            for(int i = 0 ;i < itemDate.size() ;i++){
                dc = new DateCount();
                dc.setDate(itemDate.get(i).get(0));
                dc.setPv(getCountValue(itemData.get(i).get(0)));
                dc.setUv(getCountValue(itemData.get(i).get(1)));
                dc.setNv(getCountValue(itemData.get(i).get(2)));
                dc.setIp(getCountValue(itemData.get(i).get(3)));
                listResult.add(dc);
            }
            result.setDataList(listResult);
        }
        return result;
    }

相关文章

网友评论

      本文标题:百度推广统计对接

      本文链接:https://www.haomeiwen.com/subject/otpuwqtx.html