百度推廣統(tǒng)計(jì)對(duì)接

以下所有內(nèi)容引用自CSDN:shanhanyu(侵刪)

百度推廣官方文檔地址

百度推廣-登錄接口

  1. 注冊(cè)百度統(tǒng)計(jì)賬戶,確保網(wǎng)站昨日PV大于100,開通數(shù)據(jù)導(dǎo)出服務(wù)獲得Token;

  2. 設(shè)置公鑰key(隨機(jī)生成),并進(jìn)行RSA工具類獲取公鑰;

  3. 按照文檔要求構(gòu)造請(qǐng)求參數(shù)對(duì)象req(DoLoginRequestImpl);

  4. 將請(qǐng)求參數(shù)轉(zhuǎn)換為JSON,并使用Gzip進(jìn)行壓縮;(消息頭規(guī)范)

  5. 通過(guò)RSA工具類用公鑰加密數(shù)據(jù);(消息頭規(guī)范)

  6. 通過(guò)HTTP請(qǐng)求進(jìn)行登錄,返回結(jié)果數(shù)據(jù);

  7. 解壓返回結(jié)果,獲取UCID;

百度推廣-獲取站點(diǎn)列表

  1. 通過(guò)登錄接口獲取UCID;

  2. 調(diào)用獲取站點(diǎn)列表接口;

  3. 解析響應(yīng)結(jié)果,獲取站點(diǎn)對(duì)應(yīng)的siteId,具體響應(yīng)內(nèi)容見官方文檔;

百度推廣-獲取站點(diǎn)訪問(wèn)數(shù)據(jù)

  1. 通過(guò)登錄接口和獲取站點(diǎn)列表接口得到UCID和SiteId;

  2. 拼接參數(shù), 調(diào)用數(shù)據(jù)導(dǎo)出接口;

  3. 解析響應(yīng)結(jié)果,具體響應(yīng)內(nèi)容見官方文檔;

示例代碼

實(shí)體(忽略getter/setter方法)
public class WebsiteUser implements Serializable {

    private String password;

    private String userName;

    private String token;

    private String ucid;

}
登錄接口
    /**
     * 登陸接口
     * 將登陸用戶信息進(jìn)行壓縮加密,然后登陸
     */
    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);
             //掛接方需要首先將消息轉(zhuǎn)換成 JSON 格式,編碼采用 UTF8,然后用 GZIP 對(duì)消息 JSON 進(jìn)行壓縮。壓縮完畢后,采用 RSA 算法的公鑰進(jìn)行加密。
            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請(qǐng)求封裝

    /**
     * 僅用于登陸的http post請(qǐng)求
     * @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");        //默認(rèn)是百度賬號(hào)
        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 "";
    }
獲取站點(diǎn)列表
    /**
     * 獲取當(dāng)前用戶下的站點(diǎn)列表
     * @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());
        //目前百度返回的信息結(jié)構(gòu)為 body/data/list[],但是api文檔中說(shuō)明data下僅有一個(gè)list,所以只需要返回一個(gè)第一個(gè)list中集合即可
        if(null != resp && null != resp.getHeader() && null != resp.getHeader().getSucc() && resp.getHeader().getSucc()>0){
            return resp.getBody().getData().get(0).getList();
        }
        return null;
        }
獲取訪問(wèn)數(shù)據(jù)接口
    /**
     * 查詢站點(diǎn)數(shù)據(jù)
     * @param user      用戶
     * @param siteId    站點(diǎn)ID
     * @param startDate 開始時(shí)間
     * @param endDate   結(jié)束時(shí)間
     */
    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);      //  默認(rèn)查詢?nèi)?        body.setGran(gran);
        //body.setOrder("visitor_count,desc");
        //body.setStart_index(0);   //  默認(rèn)不分頁(yè)
        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){
        
            //百度返回?cái)?shù)據(jù)中items 包含四個(gè)list 其中第一個(gè)是時(shí)間列表  第二個(gè)是數(shù)據(jù)列表  第三 第四均為空
            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;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容