今日頭條飛魚CRM (java) (獲取今日頭條上的廣告推廣數據從飛魚的CRM系統)



import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;


public class ToutiaoApi {

    

   
    private static String URL ="https://feiyu.oceanengine.com/crm/v2/openapi/pull-clues/";

    private static String api_path ="/crm/v2/openapi/pull-clues/";
    
    //祕鑰
    private static String  SECRETKEY = "";

    //token
    private static String  TOKEN = "";
                      
    //Base64
    final Base64.Encoder encoder = Base64.getEncoder();
    
    public static void main(String[] args) {
        try {
             String start_time ="2019-06-10";
             String end_time ="2019-10-23";
            new ToutiaoApi().crmPullClues(start_time,end_time,1,10);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
        /**
     * 
     * @description
     * @param startTime
     * @param endTime
     * @param page
     * @param pageSize
     * @return
     * @throws Exception
     */
    public String crmPullClues(String startTime, String endTime, int page, int pageSize) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        try {
            
            URIBuilder uriBuilder = new URIBuilder(URL);
            long Timestamp = getTimestamp();
            List<NameValuePair> list = new LinkedList<>();
            BasicNameValuePair param1 = new BasicNameValuePair("start_time", startTime);
            BasicNameValuePair param2 = new BasicNameValuePair("end_time", endTime);
            BasicNameValuePair param3 = new BasicNameValuePair("page", String.valueOf(page));
            BasicNameValuePair param4 = new BasicNameValuePair("page_size",String.valueOf(pageSize));
            list.add(param1);
            list.add(param2);
            list.add(param3);
            list.add(param4);
            uriBuilder.setParameters(list);
            
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
            httpGet.setConfig(requestConfig);
         
            // 鑑權
            String sign = this.sign(Timestamp,startTime,endTime);
            //設置頭信息
            httpGet.addHeader("Signature",sign);
            httpGet.addHeader("Timestamp",String.valueOf(Timestamp));
            httpGet.addHeader("Access-Token",TOKEN);
            
            // 瀏覽器表示
            // httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 傳輸的類型
            // httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpGet.addHeader("Content-Type", "application/json;charset=UTF-8");
            // 執行請求
            response = httpClient.execute(httpGet);
            // 獲得響應的實體對象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具類進行轉換成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            System.out.println("Http協議出現問題");
            e.printStackTrace();
        } catch (ParseException e) {
            System.out.println("解析錯誤");
            e.printStackTrace();
        } catch (URISyntaxException e) {
            System.out.println("URI解析異常");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IO異常");
            e.printStackTrace();
        } finally {
            // 釋放連接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("釋放連接出錯");
                    e.printStackTrace();
                }
            }
        }
     
        // 打印響應內容
        System.out.println(entityStr);
     
        return entityStr;
    }

   
   
    /**
     * 
     * @description 簽名
     * @param timestamp
     * @param start_time
     * @param end_time
     * @return
     * @throws Exception
     */
    private String sign(long timestamp,String start_time,String end_time) throws Exception {
        String source_data = api_path+"?start_time="+start_time+"&end_time="+end_time+" "+timestamp;
        System.out.println("source_data="+source_data);
        String SHA256 = sha256_HMAC(source_data, SECRETKEY);
        System.out.println("HMACSHA256="+SHA256);
        String base64 = encoder.encodeToString(SHA256.getBytes());//base64編碼後
        return base64;
        
    }


    
    //時間戳
    public static long getTimestamp() {
        return System.currentTimeMillis()/1000;
    }
  
    
    

      /**
       * 
       * @description 加密方法1
       * @param message
       * @param secret
       * @return
       */
      public static String sha256_HMAC(String message, String secret) {
        String hash = "";
        try {
          Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
          SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
          sha256_HMAC.init(secret_key);
          byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
          hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
          System.out.println("Error HmacSHA256 ===========" + e.getMessage());
        } 
        return hash;
      }
    

      private static String byteArrayToHexString(byte[] b) {
          StringBuilder hs = new StringBuilder();
          for (int n = 0; b != null && n < b.length; n++) {
            String stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1)
              hs.append('0'); 
            hs.append(stmp);
          } 
          return hs.toString().toLowerCase();
        }
      
      /**
       * 
       * @description HMACSHA256 加密方法2
       * @param data
       * @param key
       * @return
       * @throws Exception
       */
      public static String HMACSHA256(String data, String key) throws Exception {
          Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
          SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
          sha256_HMAC.init(secret_key);
          byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
          StringBuilder sb = new StringBuilder();
          for (byte item : array) {
              sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
          }
          return sb.toString();
      }
      
      
}

 

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