首頁 > 軟體

Java實現京東聯盟API資料獲取功能

2022-07-25 14:04:13

一:api引數

京東聯盟提供了一個SDK的包下載好加入到專案中,SDK封裝了api的呼叫方法,程式碼就是每個api的呼叫範例如下把申請的四個引數填好就行 。

String SERVER_URL = "https://api.jd.com/routerjson";
String accessToken = null;
String appKey = "";
String appSecret = "";
JdClient client=new DefaultJdClient(SERVER_URL,accessToken,appKey,appSecret);
UnionOpenGoodsJingfenQueryRequest request=new UnionOpenGoodsJingfenQueryRequest();
JFGoodsReq goodsReq=new JFGoodsReq();
goodsReq.setEliteId(1);
request.setGoodsReq(goodsReq);
request.setVersion("1.0");
UnionOpenGoodsJingfenQueryResponse response=client.execute(request);
System.out.println(response);

加入倆個依賴。

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.2</version>
</dependency>
 
<dependency>
     <groupId>org.codehaus.jackson</groupId>
     <artifactId>jackson-core-asl</artifactId>
     <version>1.9.2</version>
</dependency>

是不是按照我上面的來System.out.println(response),沒有拿到資料,就是一串包名 com.jd.open.api.sdk.response.kplunion.UnionOpenGoodsJingfenQueryResponse@1df82230不要慌,因為是在Java中集合是列印不出來的,只需要轉化為string就能出來資料。這樣String json = JSON.toJSONString(response),就出來資料了咯。

二:在一個util裡寫一個httpclient方法

    public static String doGet(String url) {
        // 建立Httpclient物件
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 建立uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 建立http GET請求
            HttpGet httpGet = new HttpGet(uri);
            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否為200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

business是入參引數前端傳入的就必須是網址格式先呼叫getBusiness,在傳參,method是地址,例jd.union.open.activity.query我用的是一個URL拼接的方法。詳情https://jos.jd.com/commontools?id=2,appKey,appSecret寫好。

private static String appKey="";
private static String appSecret="";
    public String getGoodsJingfenQuery(String business,String method) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設定日期格式
        String date = df.format(new Date());// new Date()為獲取當前系統時間,也可使用當前時間戳
        String rc =getBusinessnot(business);//把入參引數轉化成json格式
        String sj =getTime(date);//把時間轉化網址格式
        String str =appSecret+"360buy_param_json"+rc+"app_key"+appKey+"method"+method+"sign_methodmd5timestamp"+date+"v1.0"+appSecret;
        String sign=MD5(str);//獲取簽名,MD5 32位元的加密
        String url="https://api.jd.com/routerjson?360buy_param_json="+newbusiness+"&app_key="+appKey+"&method="+method+"&sign_method=md5&timestamp="+sj+"&v=1.0&sign="+sign;
        return httpClientUtil.doGet(url,null);
    }

裡面一些方法。

    public String getBusiness(String business) {
        String a = business.replace("{","%7B");
        String b = a.replace(":","%3A");
        String c = b.replace("}","%7D");
        return c.replace(""","%22");
    }
 
    public String getBusinessnot(String business) {
        String a = business.replace("%7B","{");
        String b = a.replace("%3A",":");
        String c = b.replace("%7D","}");
        return c.replace("%22",""");
    }
 
    public String getTime(String time) {
        String a = time.replace(" ","+");
        return a.replace(":","%3A");
    }
 
    public String getMD5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    public static String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

這樣就拿到了京東聯盟的資料。

有一個毒點,我用帶參的httpclient方法map<string,string> param =new treemap<>();,而不是寫一長串url,列如param.put("360buy_param_json","{"goodsReq":{"eliteId":"1"}}");我試了傳過去報json轉化異常,不知道咋解決。

到此這篇關於Java獲取京東聯盟API資料的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com