最近項目需要,要獲取淘寶商品全部類目結構,有兩種方法,1. 可以通過爬蟲技術實現, 2. 通過淘寶開放接口實現。
這里選用第2種方法,以下是實現過程:
1. 首先要申請成為淘寶開發者
2.
進入后台后,新建一個應用,得到一個app證書,證書里面有Appkey 和 Appsecret (Appsecret為 API 調用的密鑰要注意保密,如泄漏要及時重置)

3.
調用淘寶接口還需要一個 sissionid,通過以下方式得到,
訪問URL: http://container.api.taobao.com/container?appkey=你的AppKey

登錄你的淘寶賬號,授權確認后在回調的URL中即可得到sissionid

示例:http://www.xxx.com/?top_appkey=xxx&top_parameters=xxx&top_session=
你的SessionID&top_sign=xxx
4. 主程序代碼GetCategory.java
這里解析json的數據結構用到fastjson開源包(網上搜索一下,這里用的是 fastjson-1.1.34.jar ),
1 import java.text.SimpleDateFormat; 2 import java.util.Date; 3 import java.util.Iterator; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.TreeMap; 7 import java.util.regex.Matcher; 8 import java.util.regex.Pattern; 9 10 import com.alibaba.fastjson.JSONArray; 11 12 import java.io.File; 13 import java.io.FileOutputStream; 14 import java.io.IOException; 15 16 public class GetCategory { 17 //protected static String Url = "http://gw.api.tbsandbox.com/router/rest";//沙箱環境調用地址 18 protected static String Url = "http://gw.api.taobao.com/router/rest";//正式環境調用地址 19 protected static String appkey = 你的AppKey; 20 protected static String secret = 你的APPSecret; 21 protected static String session = 你的SesionID; 22 protected static File file = new File("c:/cats.txt"); 23 protected static FileOutputStream fop = null; 24 25 //調用淘寶接口,獲取父目錄下的子目錄(以json數據格式返回) 26 public static String getCat(String parent_cid){ 27 TreeMap<String, String> apiparamsMap = new TreeMap<String, String>(); 28 apiparamsMap.put("format", "json");//以json數據格式返回 29 apiparamsMap.put("method", "taobao.itemcats.get"); //獲取類目函數 30 apiparamsMap.put("sign_method","md5"); 31 apiparamsMap.put("app_key",appkey); //appkey 32 apiparamsMap.put("v", "2.0");//版本 33 apiparamsMap.put("session",session);//sessionID 34 String timestamp =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); 35 apiparamsMap.put("timestamp",timestamp);//時間 36 37 apiparamsMap.put("fields","cid,parent_cid,name,is_parent");//需要獲取的字段 38 apiparamsMap.put("parent_cid",parent_cid); //父目錄id 39 40 //生成簽名 41 String sign = Util.md5Signature(apiparamsMap,secret); 42 apiparamsMap.put("sign", sign); 43 StringBuilder param = new StringBuilder(); 44 for (Iterator<Map.Entry<String, String>> it = apiparamsMap.entrySet() 45 .iterator(); it.hasNext();) { 46 Map.Entry<String, String> e = it.next(); 47 param.append("&").append(e.getKey()).append("=").append(e.getValue()); 48 } 49 return param.toString().substring(1); 50 } 51 52 //根據父目錄遞歸獲取子目錄,並寫入txt文件 53 public static void getAllCats(String root) throws IOException{ 54 String result = Util.getResult(Url,getCat(root)); 55 //System.out.print(result); 56 if(result == null || result.length()==0) 57 { 58 System.out.print("root:"+ root + " result null");//獲取不到,記錄下來后面再手動補充 59 return; 60 } 61 // String result ="{\"itemcats_get_response\":{\"item_cats\":{\"item_cat\":[{\"cid\":121266001,\"is_parent\":true,\"name\":\"眾籌\",\"parent_cid\":0}," 62 // + "{\"cid\":120950001,\"is_parent\":true,\"name\":\"保險分銷\",\"parent_cid\":0}," 63 // + "{\"cid\":124470006,\"is_parent\":true,\"name\":\"平行進口車\",\"parent_cid\":0}]},\"request_id\":\"ze1ym5zcokd2\"}}"; 64 Pattern p = Pattern.compile("\"item_cat\":(.*)},\"request_id\":");//提取item_cat部分內容 65 Matcher m = p.matcher(result); 66 if (m.find()) { 67 String catsJsonstr = m.group(1); 68 List<item_cat> cats = JSONArray.parseArray(catsJsonstr, item_cat.class); 69 for (int i = 0; i < cats.size(); i++) { 70 item_cat cat = cats.get(i); 71 String content = cat.cid + "," + cat.name + "," + cat.parent_cid + "," + cat.is_parent + "\r\n";//寫入內容,一個類目一行記錄 72 byte[] contentInBytes = content.getBytes(); 73 fop.write(contentInBytes);//寫入文件 74 fop.flush(); 75 if (cat.is_parent.equals("true")) { 76 getAllCats(cat.cid); 77 } 78 } 79 } 80 } 81 82 public static void getTaobaoCats() { 83 try { 84 //打開文件 85 fop = new FileOutputStream(file); 86 // if file doesn't exists, then create it 87 if (!file.exists()) { 88 file.createNewFile(); 89 } 90 //獲取頂層根目錄(0) 91 getAllCats("0"); 92 //關閉文件 93 fop.close(); 94 System.out.println("Done"); 95 } catch (IOException e) { 96 e.printStackTrace(); 97 } 98 } 99 100 public static void main(String[] args) { 101 //獲取所有類目,並寫入txt文件 102 getTaobaoCats(); 103 } 104 }
代碼中用到的類目的實體類:item_cat.java
1 public class item_cat { 2 /** 3 * 類目id 4 */ 5 public String cid; 6 /** 7 * 是否為父目錄 8 */ 9 public String is_parent; 10 /** 11 * 父目錄ID 12 */ 13 public String parent_cid; 14 /** 15 * 目錄名稱 16 */ 17 public String name; 18 public item_cat() { 19 super(); 20 // TODO Auto-generated constructor stub 21 } 22 public item_cat(String cid, String is_parent, String parent_cid, String name) { 23 super(); 24 this.cid = cid; 25 this.is_parent = is_parent; 26 this.parent_cid = parent_cid; 27 this.name = name; 28 } 29 public String getCid() { 30 return cid; 31 } 32 public void setCid(String cid) { 33 this.cid = cid; 34 } 35 public String getIs_parent() { 36 return is_parent; 37 } 38 public void setIs_parent(String is_parent) { 39 this.is_parent = is_parent; 40 } 41 public String getName() { 42 return name; 43 } 44 public void setName(String name) { 45 this.name = name; 46 } 47 @Override 48 public String toString() { 49 return "item_cat [cid=" + cid + ", is_parent=" + is_parent + ", parent_cid=" + parent_cid + ", name=" + name + "]"; 50 } 51 }
最后獲取到的文件內數據格式如下:
類目ID,類目名稱,父類目ID,是否為父目錄
121266001,眾籌,0,true
121278001,影音,121266001,false
121280001,公益,121266001,false
121274002,書籍,121266001,false
121284001,娛樂,121266001,false
121288001,科技,121266001,false
...
剛好是一張自關聯的目錄結構表。