淘宝网开放平台API(taobao.items.all.get)调用示例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.Web.Security;
using System.IO;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        string _app_key = "12000000";
        string _app_secret = "65a854182f30c16ef7191f0a7920e02e";
        string _session = string.Empty;//SessionKey

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //获取授权码
            //      1.测试环境获取接口
            //              地址:http://open.taobao.com/isv/authorize.php?appkey={appkey}
            //              返回:PpAE1wquKJoxTtYyJUszOTTfIK5NTpxPVde868d74ZzcC1g%2BdcT6AHycEImgh%2FaN18DSSoVAs10FUz7W20jEU6PXModetBXgsjnSbouwz18pF9BuV%2ByqSwcX%2FJE5cffJ5aGu30nIS%2BxtW8t6gZ7QqA%3D%3D
            //
            //      2.正式环境获取接口
            //              地址:http://auth.open.taobao.com/?appkey={appkey}
            //              返回:TOP-108f466f8db48810c043cbb7ef34f28130flrefw2NuyN3RAR8MrAa6lNwBkW5XZ-END
            System.Diagnostics.Process.Start("iexplore.exe", "http://auth.open.taobao.com/?appkey=" + _app_key);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            GetSessionKey(textBox1.Text);

            if (_session != string.Empty)
                MessageBox.Show("登录成功!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 根据授权码获取SessionKey
        /// </summary>
        /// <param name="authcode"></param>
        /// <returns></returns>
        void GetSessionKey(string authcode)
        {
            _session = string.Empty;

            try
            {
                //获取SessionKey
                //      1.测试环境获取地址
                //              地址:http://container.api.tbsandbox.com/container?authcode={授权码}
                //              返回:top_appkey=12000000&top_parameters=aWZyYW1lPTAmdHM9MTI1NDA0NTAyMDU2MCZ2aWV3X21vZGU9ZnVsbCZ2aWV3X3dpZHRoPTAmdmlzaXRvcl9pZD0xNzU3NTQzNTEmdmlzaXRvcl9uaWNrPWFsaXB1YmxpYzAx&top_session=111d69c3f3986ea50da9ebf254aa5d1d1&top_sign=S+ZSl9gA/r1fPGv9p6wrGw==
                //
                //      2.正式环境获取地址
                //              地址:http://container.open.taobao.com/container?authcode={授权码}
                //              返回:top_appkey=12000000&top_parameters=aWZyYW1lPTAmdHM9MTI1NDExNjMwODcwMyZ2aWV3X21vZGU9ZnVsbCZ2aWV3X3dpZHRoPTAmdmlzaXRvcl9pZD0yMDA4NTYyMjYmdmlzaXRvcl9uaWNrPcLM0ray6M/j&top_session=1530118c532e224ff266240d2402e99a8&top_sign=CCB17zkYCGZnKnStwJ/5VA==
                WebRequest webRequest = WebRequest.Create(new Uri("http://container.open.taobao.com/container?authcode=" + authcode));
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Method = "POST";
                webRequest.Timeout = 5000;

                WebResponse webResponse = webRequest.GetResponse();
                using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    string text = streamReader.ReadToEnd();

                    Match match = Regex.Match(text, @"top_session=([\w]+)");
                    if (match.Success)
                    {
                        _session = match.Groups[1].Value;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "消息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //1.应用信息


            //2.参数集

            SortedList<string, string> parameters = new SortedList<string, string>();

            //2.1 应用级输入参数
            parameters.Add("fields", "iid,title,list_time,delist_time,has_showcase");

            //2.2 系统级参数
            parameters.Add("method", "taobao.items.all.get");
            parameters.Add("session", _session);
            parameters.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            parameters.Add("format", "xml");
            parameters.Add("app_key", _app_key);
            parameters.Add("v", "1.0");

            //2.3 生成sign,格式: app_secret参数1值1参数2值2,生成md5后转为大写
            StringBuilder sb = new StringBuilder();
            sb.Append(_app_secret);
            foreach (KeyValuePair<string, string> item in parameters)
            {
                sb.Append(item.Key + item.Value);
            }
            parameters.Add("sign", FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "MD5").ToUpper());

            //3.生成url
            string url = "http://gw.api.taobao.com/router/rest?";//线上环境: http://gw.api.taobao.com/router/rest  测试环境: http://gw.sandbox.taobao.com/router/rest
            StringBuilder query = new StringBuilder();
            foreach (KeyValuePair<string, string> item in parameters)
            {
                query.Append(item.Key + "=" + System.Web.HttpUtility.UrlEncode(item.Value, System.Text.Encoding.UTF8) + "&");
            }
            url += query.ToString().TrimEnd(new char[] { '&' });

            //4.淘宝客商品查询
            try
            {
                WebRequest webRequest = WebRequest.Create(new Uri(url));
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Method = "POST";
                webRequest.Timeout = 5000;
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(((WebResponse)webRequest.GetResponse()).GetResponseStream());

                textBox2.Text = xmlDocument.InnerXml;
            }
            catch (Exception ex)
            {
                textBox2.Text = ex.Message;
            }
        }
    }
}


评论: 0 | 引用: 0 | 查看次数: 7171
发表评论
登录后再发表评论!