本文介绍淘宝联盟服务Java SDK的使用方法及示例。

接口列表

接口名称

接口说明

SearchByPic

用于向淘宝联盟版在线调用,根据图片查询。

SearchByUrl

用于向淘宝联盟版在线调用,根据图片URL查询。

GetProductInfoByIds

用于向淘宝联盟版在线调用,根据ID查询商品。

准备工作

  • 在安装和使用阿里云SDK前,确保您已经注册阿里云账号并生成访问密钥(AccessKey)。详情请参见

    创建AccessKey

  • 将SDK添加到项目中引入ImageSearch SDK依赖,通过Maven二方库依赖的方式将ImageSearch的SDK加入到自己的项目中。

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>imagesearch20210501</artifactId>
  <version>1.2.2</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>ccc20200701</artifactId>
  <version>2.6.7</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.83_noneautotype</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-qualitycheck</artifactId>
  <version>3.0.7</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.6</version>
</dependency>

SearchByPic接口

  • 代码示例

import com.alibaba.fastjson.JSON;
import com.aliyun.imagesearch20210501.Client;
import com.aliyun.imagesearch20210501.models.SearchByPicAdvanceRequest;
import com.aliyun.imagesearch20210501.models.SearchByPicResponse;
import com.aliyun.imagesearch20210501.models.SearchByPicResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;


public class SearchByPic {
    private static final String PIC_NAME = "C:\\xxx/9.jpg";

    private static final String PIC_URL = "https://ossname.oss-cn-shanghai.aliyuncs.com/m.jpg";

    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();
        // 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
        // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
        // 本示例以将AccessKey ID和AccessKey Secret保存在环境变量为例说明。您也可以根据业务需要,保存到配置文件里。
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");

        authConfig.endpoint = "imagesearch.cn-shanghai.aliyuncs.com";
        authConfig.regionId = "cn-shanghai";
        Client client = new Client(authConfig);
        SearchByPicAdvanceRequest request = new SearchByPicAdvanceRequest();

        InputStream inputStream = new FileInputStream(PIC_NAME);

        request.picContentObject = inputStream;
        // 必填 PID
        request.pid = "mm_xxxx_xxxx_xxxx";
        // 需要返回的字段list。不同的字段用逗号分割。默认PicUrl,ReservePrice,Title,Url,ZkFinalPrice字段必返回。
        request.fields = "Title,PicUrl,ReservePrice,ZkFinalPrice,UserType,Provcity,Nick,SellerId,Volume,LevelOneCategoryName,CategoryName,CouponTotalCount,CouponRemainCount,CouponStartTime,CouponEndTime,CouponStartFee,CouponAmount,CouponInfo,CommissionRate,CouponShareUrl,Url,ShopTitle";
        // 图片类目
        //request.categoryId = 88888888;
        // 是否需要进行主体识别。默认true
        //request.crop = false;
        // 图片的主体区域,格式为x1,x2,y1,y2
        //request.region = "518,1524,398,1632";

        // 选填,返回结果的起始位置。取值范围:0-499。默认值:0。
        request.start = 0;

        // 选填,返回结果的数目。取值范围:1-20。默认值:10。
        request.num = 2;

        // 渠道ID。用于淘宝联盟中的渠道区分。
        //request.relationId = 1145;

        // 2 创建RuntimeObject实例并设置运行参数
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        runtimeOptions.autoretry = true;
        try {
            SearchByPicResponse response = client.searchByPicAdvance(request, runtimeOptions);
            System.out.println("requestID:" + response.getBody().getRequestId());
            System.out.println("code:" + response.getBody().getCode());
            System.out.println("message:" + response.getBody().getMessage());
            List<SearchByPicResponseBody.SearchByPicResponseBodyDataAuctions> auctions = response.getBody().getData().getAuctions();
            for (SearchByPicResponseBody.SearchByPicResponseBodyDataAuctions auction : auctions) {
                System.out.println("---------------");
                System.out.println(auction.getRankScore());
                SearchByPicResponseBody.SearchByPicResponseBodyDataAuctionsResult result = auction.getResult();
                System.out.println("result:" + result.toMap());
            }

            SearchByPicResponseBody.SearchByPicResponseBodyPicInfo picInfo = response.getBody().getPicInfo();
            System.out.println("---------------");
            SearchByPicResponseBody.SearchByPicResponseBodyPicInfoMainRegion mainRegion = picInfo.getMainRegion();
            for (SearchByPicResponseBody.SearchByPicResponseBodyPicInfoMainRegionMultiCategoryId categoryId : mainRegion.getMultiCategoryId()) {
                // 主体区域预测类目
                System.out.println("mainRegion categoryId: " + categoryId.getCategoryId());
                // 主体区域预测类目分值打分
                System.out.println("mainRegion score: " + categoryId.getScore());
            }
            System.out.println("---------------");
            System.out.println("mainRegion region: " + mainRegion.getRegion());
            System.out.println("---------------");
            List<SearchByPicResponseBody.SearchByPicResponseBodyPicInfoMultiRegion> multiCategoryIds = picInfo.getMultiRegion();
            if (null != multiCategoryIds) {
                for (SearchByPicResponseBody.SearchByPicResponseBodyPicInfoMultiRegion c : multiCategoryIds) {
                    // 多主体识别区域
                    System.out.println("multi region: " + c.getRegion());
                }
            }

        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getData());
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
        }
    }
}

  • 结果示例

requestID:xx-39E6-xx-B474-xx
code:0
message:null
---------------
0.9877
result:{"categoryName":"USB风扇","commissionRate":"90","couponAmount":2,"couponEndTime":"2021-08-31","couponInfo":"满15.0元减2.0元","couponRemainCount":69510,"couponShareUrl":"//uland.taobao.com/coupon/edetail?exxxxx","couponStartFee":"15.000000","couponStartTime":"2021-07-06","couponTotalCount":"100000","levelOneCategoryName":"3C数码配件",nick":"旗舰店","picUrl":"//img.alicdn.com/i2pic.jpg","provcity":"广东深圳","reservePrice":"65.8","sellerId":"2207366944297","shopTitle":"旗舰店","title":"【官方推荐】电风扇","url":"//s.click.taobao.com/t?zzzzz","userType":1,"volume":12420,"zkFinalPrice":"15.8"}
---------------
mainRegion categoryId: 88888888
mainRegion score: 0.79521
mainRegion categoryId: 22
mainRegion score: 0.13365
mainRegion categoryId: 9
mainRegion score: 0.00778
mainRegion categoryId: 7
mainRegion score: 0.00685
---------------
mainRegion region: 428,750,64,739
---------------
multi region: 428,750,64,739
multi region: 428,750,64,739

SearchByUrl接口

  • 代码示例

package com.example.imagesearch20210501;

import com.alibaba.fastjson.JSON;
import com.aliyun.imagesearch20210501.Client;
import com.aliyun.imagesearch20210501.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;


public class SearchByUrl {
    private static final String PIC_NAME = "C:\\xx/99.jpg";

    private static final String PIC_URL = "http://img.alicdn.com/10.jpg";

    public static void main(String[] args) throws Exception {
        Config authConfig = new Config();

        // 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
        // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
        // 本示例以将AccessKey ID和AccessKey Secret保存在环境变量为例说明。您也可以根据业务需要,保存到配置文件里。
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");

        authConfig.endpoint = "imagesearch.cn-shanghai.aliyuncs.com";
        authConfig.regionId = "cn-shanghai";
        Client client = new Client(authConfig);
        SearchByUrlRequest request = new SearchByUrlRequest();
        // 必填 PID
        request.pid = "mm_xx_xx_xx";
        request.picUrl = PIC_URL;
        // 需要返回的字段list。不同的字段用逗号分割。默认PicUrl,ReservePrice,Title,Url,ZkFinalPrice字段必返回。
        // request.fields = "Title,PicUrl,ReservePrice,ZkFinalPrice,UserType,Provcity,Nick,SellerId,Volume,LevelOneCategoryName,CategoryName,CouponTotalCount,CouponRemainCount,CouponStartTime,CouponEndTime,CouponStartFee,CouponAmount,CouponInfo,CommissionRate,CouponShareUrl,Url,ShopTitle";
        // 图片类目
        // request.categoryId = 8;
        // 是否需要进行主体识别。默认true
        //request.crop = false;
        // 图片的主体区域,格式为x1,x2,y1,y2
        // request.region = "88,266,59,517";
        // 选填,返回结果的起始位置。取值范围:0-499。默认值:0。
        // request.start = 1;
        // 选填,返回结果的数目。取值范围:1-20。默认值:10。
        //request.num = 20;
        // 渠道ID。用于淘宝联盟中的渠道区分。
        //request.relationId = 1145;
        try {
            SearchByUrlResponse response = client.searchByUrl(request);
            System.out.println("requestID:" + response.getBody().getRequestId());
            System.out.println("code:" + response.getBody().getCode());
            System.out.println("message:" + response.getBody().getMessage());
            List<SearchByUrlResponseBody.SearchByUrlResponseBodyDataAuctions> auctions = response.getBody().getData().getAuctions();
            for (SearchByUrlResponseBody.SearchByUrlResponseBodyDataAuctions auction : auctions) {
                System.out.println("---------------");
                System.out.println(auction.getRankScore());
                SearchByUrlResponseBody.SearchByUrlResponseBodyDataAuctionsResult result = auction.getResult();
                System.out.println("result:" + result.toMap());
            }

            SearchByUrlResponseBody.SearchByUrlResponseBodyPicInfo picInfo = response.getBody().getPicInfo();
            System.out.println("---------------");
            SearchByUrlResponseBody.SearchByUrlResponseBodyPicInfoMainRegion mainRegion = picInfo.getMainRegion();
            List<SearchByUrlResponseBody.SearchByUrlResponseBodyPicInfoMultiRegion> multiRegion = picInfo.getMultiRegion();
            for (SearchByUrlResponseBody.SearchByUrlResponseBodyPicInfoMainRegionMultiCategoryId categoryId : mainRegion.getMultiCategoryId()) {
                // 主体区域预测类目
                System.out.println("mainRegion categoryId: " + categoryId.getCategoryId());
                // 主体区域预测类目分值打分
                System.out.println("mainRegion score: " + categoryId.getScore());
            }
            System.out.println("---------------");
            System.out.println("mainRegion region: " + mainRegion.getRegion());
            System.out.println("---------------");
            if (null != mainRegion) {
                for (SearchByUrlResponseBody.SearchByUrlResponseBodyPicInfoMultiRegion c : multiRegion) {
                    // 多主体识别区域
                    System.out.println("multi region: " + c.getRegion());
                }
            }

        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getData());
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 结果示例

requestID:xx-8FA5-xx-BCA3-xxx
code:0
message:null
---------------
0.8961
result:{"categoryName":"USB风扇","commissionRate":"90","couponAmount":2,"couponEndTime":"2021-08-31","couponInfo":"满15.0元减2.0元","couponRemainCount":69510,"couponShareUrl":"//uland.taobao.com/coupon/edetail?exxxxx","couponStartFee":"15.000000","couponStartTime":"2021-07-06","couponTotalCount":"100000","levelOneCategoryName":"3C数码配件",nick":"旗舰店","picUrl":"//img.alicdn.com/i2pic.jpg","provcity":"广东深圳","reservePrice":"65.8","sellerId":"2207366944297","shopTitle":"旗舰店","title":"【官方推荐】电风扇","url":"//s.click.taobao.com/t?zzzzz","userType":1,"volume":12420,"zkFinalPrice":"15.8"}
---------------
mainRegion categoryId: 2
mainRegion score: 0.8921
mainRegion categoryId: 21
mainRegion score: 0.04188
mainRegion categoryId: 0
mainRegion score: 0.01173
mainRegion categoryId: 88888888
mainRegion score: 0.00574
---------------
mainRegion region: 60,284,147,302
---------------
multi region: 60,284,147,302
multi region: 174,293,4,145

Process finished with exit code 0

GetProductInfoByIds接口

  • 代码示例

package com.example.imagesearch20210501;

import com.alibaba.fastjson.JSON;
import com.aliyun.imagesearch20210501.Client;
import com.aliyun.imagesearch20210501.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;


public class GetProductInfoByIds {
   
public static void main(String[] args) throws Exception {
       Config authConfig = new Config();
        // 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
        // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
        // 本示例以将AccessKey ID和AccessKey Secret保存在环境变量为例说明。您也可以根据业务需要,保存到配置文件里。
        authConfig.accessKeyId = System.getenv("CC_AK_ENV");
        authConfig.accessKeySecret = System.getenv("CC_SK_ENV");

        authConfig.endpoint = "imagesearch.cn-shanghai.aliyuncs.com";
        authConfig.regionId = "cn-shanghai";
        Client client = new Client(authConfig);
        GetProductInfoByIdsRequest request = new GetProductInfoByIdsRequest();
        // 必填,PID
        request.pid = "mm_1_22514002231_23112_11123123115";
        // 必填商品ID串,用','分割,最大40个。
        request.setItemIds("xxxxxxxxxx");
        // 需要返回的字段list,不同的字段用逗号分割.默认PicUrl,ReservePrice,Title,Url,ZkFinalPrice
        request.fields = "CommissionRate";
        try {
            GetProductInfoByIdsResponse response = client.getProductInfoByIds(request);
            System.out.println(JSON.toJSONString(response.getBody()));
        } catch (TeaException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
}
        
}

  • 结果示例

  {
        "code": 0,
        "data": {
            "auctions": [
                {
                    "result": {
                        "commissionRate": "300",
                        "maxCommission": {
                            
                        },
                        "picUrl": "xx.jpg",
                        "reservePrice": "35",
                        "title": "xxxx",
                        "url": "xxxxx",
                        "zkFinalPrice": "28"
                    }
                }
            ]
        },
        "requestId": "xxx-D936-xxx-9823-xx",
        "success": true
    }