淘宝API客户端调用接口demo

有兴趣开发阿里软件的朋友来看了,这是一个官方demo:基于java语言的,用淘宝API客户端1.0版本,调用接口taobao.items.onsale.get,获取卖家出售中的商品列表
代码如下:
/**
 * 
 */
package com.taobao.api.demo.onsale;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.taobao.api.TaobaoApiException;
import com.taobao.api.TaobaoJsonRestClient;
import com.taobao.api.TaobaoRestClient;
import com.taobao.api.model.ItemsGetResponse;
import com.taobao.api.model.ItemsOnSaleGetRequest;

/**
 * @version 2008-10-29
 * @author <a href="mailto:[email protected]">zixue</a>
 * 
 */
public class MainServlet extends HttpServlet {
	private static final transient Log log = LogFactory
			.getLog(MainServlet.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 8839099738909766274L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String appkey = req.getParameter("appkey");
		String secret = req.getParameter("secret");
		if (log.isDebugEnabled()) {
			log.debug(appkey + ":" + secret);
		}
		if (appkey != null && secret != null) {
			try {
			//生成客户端实例
				TaobaoRestClient client = new TaobaoJsonRestClient(appkey,secret);
				//淘宝卖家的出售的商品列表
				ItemsOnSaleGetRequest tbReq = new ItemsOnSaleGetRequest()
						.withFields("iid,title,price,list_time,num")
						.withPageNo(1)
						.withPageSize(20);
				// use appkey as session_id
				ItemsGetResponse tbRsp = client.itemsOnSaleGet(tbReq, appkey);//搜索单个商品信息的Request请求
				if (log.isDebugEnabled()) {
					log.debug(tbRsp.getBody());
				}
				//如果接口调用成功
				if (!tbRsp.isSuccess()) {
					if (tbRsp.isRedirect()) {
						req.setAttribute("url",
										 tbRsp.getRedirectUrl(URLEncoder
															  .encode
															  (req.getRequestURL()
															      .append('?')
																  .append("appkey=")
																  .append(appkey)
																  .append("&secret=")
																  .append(secret)
															      .toString(),"utf-8")
															 )
										);
					} else {
						req.setAttribute("msg", tbRsp.getMsg());
					}
				} else {
					req.setAttribute("items", tbRsp.getItems());
				}
			} catch (TaobaoApiException e) {
				throw new ServletException(e);
			}
		}
		req.getRequestDispatcher("main.jsp").forward(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

}

你可能感兴趣的:(apache,.net,jsp,servlet)