通过Java/SOAP实现亚马逊产品广告API

t3irkdon  于 2023-02-18  发布在  Java
关注(0)|答案(4)|浏览(131)

我一直在玩亚马逊的产品广告API,我不能得到一个请求,通过给予我的数据。我一直在工作了这个:http://docs.amazonwebservices.com/AWSECommerceService/2011-08-01/GSG/和这个:Amazon Product Advertising API signed request with Java
下面是我的代码。我使用以下代码生成了SOAP绑定:http://docs.amazonwebservices.com/AWSECommerceService/2011-08-01/GSG/YourDevelopmentEnvironment.html#Java
在类路径上,我只有:commons-codec.1.5.jar

import com.ECS.client.jax.AWSECommerceService;
import com.ECS.client.jax.AWSECommerceServicePortType;
import com.ECS.client.jax.Item;
import com.ECS.client.jax.ItemLookup;
import com.ECS.client.jax.ItemLookupRequest;
import com.ECS.client.jax.ItemLookupResponse;
import com.ECS.client.jax.ItemSearchResponse;
import com.ECS.client.jax.Items;

public class Client {

    public static void main(String[] args) {
        
        String secretKey = <my-secret-key>;
        String awsKey = <my-aws-key>;
        
        System.out.println("API Test started");

        AWSECommerceService service = new AWSECommerceService();
        service.setHandlerResolver(new AwsHandlerResolver(
                secretKey)); // important
        AWSECommerceServicePortType port = service.getAWSECommerceServicePort();

        // Get the operation object:
        com.ECS.client.jax.ItemSearchRequest itemRequest = new com.ECS.client.jax.ItemSearchRequest();

        // Fill in the request object:
        itemRequest.setSearchIndex("Books");
        itemRequest.setKeywords("Star Wars");
        // itemRequest.setVersion("2011-08-01");
        com.ECS.client.jax.ItemSearch ItemElement = new com.ECS.client.jax.ItemSearch();
        ItemElement.setAWSAccessKeyId(awsKey);
        ItemElement.getRequest().add(itemRequest);

        // Call the Web service operation and store the response
        // in the response object:
        com.ECS.client.jax.ItemSearchResponse response = port
                .itemSearch(ItemElement);

        String r = response.toString();
        System.out.println("response: " + r);

        for (Items itemList : response.getItems()) {
            System.out.println(itemList);
            for (Item item : itemList.getItem()) {
                System.out.println(item);
            }
        }

        System.out.println("API Test stopped");

    }
}

以下是我得到的...我希望看到一些星星大战的书籍可以在亚马逊倾倒到我的控制台:-/:

API Test started
response: com.ECS.client.jax.ItemSearchResponse@7a6769ea
com.ECS.client.jax.Items@1b5ac06e
API Test stopped

我做错了什么(注意,第二个for循环中没有“item”被打印出来,因为它是空的)?我如何解决这个问题或获得相关的错误信息?

2w2cym1i

2w2cym1i1#

我不使用SOAP API,但您的Bounty需求并没有说明它必须使用SOAP,只有当您想调用Amazon并获得结果时才能使用。因此,我将使用REST API发布这个工作示例,它至少可以满足您的需求:
我想一些工作示例代码,击中亚马逊服务器,并返回结果
您需要下载以下文件以满足签名要求:
http://associates-amazon.s3.amazonaws.com/signed-requests/samples/amazon-product-advt-api-sample-java-query.zip
解压缩并获取com.amazon.advertising.api.sample.SignedRequestsHelper.java文件,然后将其直接放入您的项目中。
您还需要从下面下载Apache Commons Codec 1.3并将其添加到您的类路径中,即添加到您项目的库中。注意,这是Codec的唯一版本,可以与上述类(SignedRequestsHelper)一起使用。
http://archive.apache.org/dist/commons/codec/binaries/commons-codec-1.3.zip
现在,您可以复制并粘贴以下内容,确保使用正确的软件包名称替换your.pkg.here,并替换SECRETKEY属性:

package your.pkg.here;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Main {

    private static final String SECRET_KEY = "<YOUR_SECRET_KEY>";
    private static final String AWS_KEY = "<YOUR_KEY>";

    public static void main(String[] args) {
        SignedRequestsHelper helper = SignedRequestsHelper.getInstance("ecs.amazonaws.com", AWS_KEY, SECRET_KEY);

        Map<String, String> params = new HashMap<String, String>();
        params.put("Service", "AWSECommerceService");
        params.put("Version", "2009-03-31");
        params.put("Operation", "ItemLookup");
        params.put("ItemId", "1451648537");
        params.put("ResponseGroup", "Large");

        String url = helper.sign(params);
        try {
            Document response = getResponse(url);
            printResponse(response);
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static Document getResponse(String url) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(url);
        return doc;
    }

    private static void printResponse(Document doc) throws TransformerException, FileNotFoundException {
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        Properties props = new Properties();
        props.put(OutputKeys.INDENT, "yes");
        trans.setOutputProperties(props);
        StreamResult res = new StreamResult(new StringWriter());
        DOMSource src = new DOMSource(doc);
        trans.transform(src, res);
        String toString = res.getWriter().toString();
        System.out.println(toString);
    }
}

正如你所看到的,这比SOAP API更容易设置和使用,如果你对使用SOAP API没有特殊的要求,那么我强烈建议你使用REST API。
使用API的一个缺点是结果不能被解组为对象,这可以通过基于wsdl创建所需的类来弥补。

dz6r00yl

dz6r00yl2#

这结束了工作(我不得不添加我的associateTag到请求):

public class Client {

    public static void main(String[] args) {

        String secretKey = "<MY_SECRET_KEY>";
        String awsKey = "<MY AWS KEY>";

        System.out.println("API Test started");

        AWSECommerceService service = new AWSECommerceService();
        service.setHandlerResolver(new AwsHandlerResolver(secretKey)); // important
        AWSECommerceServicePortType port = service.getAWSECommerceServicePort();

        // Get the operation object:
        com.ECS.client.jax.ItemSearchRequest itemRequest = new com.ECS.client.jax.ItemSearchRequest();

        // Fill in the request object:
        itemRequest.setSearchIndex("Books");
        itemRequest.setKeywords("Star Wars");
        itemRequest.getResponseGroup().add("Large");
//      itemRequest.getResponseGroup().add("Images");
        // itemRequest.setVersion("2011-08-01");
        com.ECS.client.jax.ItemSearch ItemElement = new com.ECS.client.jax.ItemSearch();
        ItemElement.setAWSAccessKeyId(awsKey);
        ItemElement.setAssociateTag("th0426-20");
        ItemElement.getRequest().add(itemRequest);

        // Call the Web service operation and store the response
        // in the response object:
        com.ECS.client.jax.ItemSearchResponse response = port
                .itemSearch(ItemElement);

        String r = response.toString();
        System.out.println("response: " + r);

        for (Items itemList : response.getItems()) {
            System.out.println(itemList);

            for (Item itemObj : itemList.getItem()) {

                System.out.println(itemObj.getItemAttributes().getTitle()); // Title
                System.out.println(itemObj.getDetailPageURL()); // Amazon URL
            }
        }

        System.out.println("API Test stopped");

    }
}
p4tfgftt

p4tfgftt3#

看起来response对象并没有覆盖toString(),所以如果它包含了某种错误响应,简单地打印它并不能告诉你错误响应是什么。你需要查看API,看看response对象返回了哪些字段,然后单独打印这些字段。要么你会得到一个明显的错误消息,要么你必须回到他们的文档来找出错误。

7tofc5zh

7tofc5zh4#

您需要调用Item对象上的get方法来检索其详细信息,例如:

for (Item item : itemList.getItem()) {
   System.out.println(item.getItemAttributes().getTitle()); //Title of item
   System.out.println(item.getDetailPageURL()); // Amazon URL
   //etc
}

如果有任何错误,您可以通过调用getErrors()获取它们

if (response.getOperationRequest().getErrors() != null) { 
  System.out.println(response.getOperationRequest().getErrors().getError().get(0).getMessage());
}

相关问题