淘宝登录及多线程同步

本文详细探讨了在淘宝登录过程中如何利用多线程技术实现同步操作,深入解析了多线程同步的关键点,包括线程安全、锁机制和并发控制,同时结合具体实例展示了在实际应用中的解决方案。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using APITest;
using System.Threading;


namespace TBApiLoginC
{
    public partial class TBCForm : Form
    {
        public TBCForm()
        {
            InitializeComponent();
        }
        public delegate void CallBackDelegate(string message);
        string s;
        Thread t1, t2; // 说明为窗体类成员
        int h;
        private void adds(object o)
         {
             
             string appkey = "XX";
             string secret = "XX";
             string session = "XX";
 
             IDictionary<string, string> param = new Dictionary<string, string>();
             param.Add("fields","nick,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id");
             // param.Add("nick", "sandbox_c_1");
 
             //Util.Post 集成了 系统参数 和 计算 sign的方法
             s = Util.Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.items.onsale.get", session, param);
            // MessageBox.Show(s);
             CallBackDelegate cbd =o as CallBackDelegate;
             //执行回调.
             cbd(s);
             h = 1;
         }


        //回调方法
        private void CallBack(string message)
        {
            //主线程报告信息,可以根据这个信息做判断操作,执行不同逻辑.
          //  MessageBox.Show(message);
            richTextBox1.Text = s;
        }

        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
         {
             CheckForIllegalCrossThreadCalls = false;  //在你的方法中加入这句话
   
             //把回调的方法给委托变量
             CallBackDelegate cbd = CallBack;
             //启动线程
             Thread th = new Thread(adds);
             th.Start(cbd);//开始线程,代入参数
             

         }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void TBCForm_ControlRemoved(object sender, ControlEventArgs e)
        {

        }
    }
}
Util.cs
using System;
using System.Net;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Xml;
using System.Security.Cryptography;

namespace APITest
{
    public class Util
    {
        /// <summary>
        /// 给TOP请求签名 API v2.0
        /// </summary>
        /// <param name="parameters">所有字符型的TOP请求参数</param>
        /// <param name="secret">签名密钥</param>
        /// <returns>签名</returns>
        protected static string CreateSign(IDictionary<string, string> parameters, string secret)
        {
            parameters.Remove("sign");

            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            StringBuilder query = new StringBuilder(secret);
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append(value);
                }
            }
            query.Append(secret);

            MD5 md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));

            StringBuilder result = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                string hex = bytes[i].ToString("X");
                if (hex.Length == 1)
                {
                    result.Append("0");
                }
                result.Append(hex);
            }

            return result.ToString();
        }


        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        protected static string PostData(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(Uri.EscapeDataString(value));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }


        /// <summary>
        /// TOP API POST 请求
        /// </summary>
        /// <param name="url">请求容器URL</param>
        /// <param name="appkey">AppKey</param>
        /// <param name="appSecret">AppSecret</param>
        /// <param name="method">API接口方法名</param>
        /// <param name="session">调用私有的sessionkey</param>
        /// <param name="param">请求参数</param>
        /// <returns>返回字符串</returns>
        public static string Post(string url, string appkey, string appSecret, string method, string session,

        IDictionary<string, string> param)
        {

            #region -----API系统参数----

            param.Add("app_key", appkey);
            param.Add("method", method);
            param.Add("session", session);
            param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            param.Add("format", "xml");
            param.Add("v", "2.0");
            param.Add("sign_method", "md5");
            param.Add("sign", CreateSign(param, appSecret));

            #endregion

            string result = string.Empty;

            #region ---- 完成 HTTP POST 请求----

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.KeepAlive = true;
            req.Timeout = 300000;
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Stream stream = null;
            StreamReader reader = null;
            stream = rsp.GetResponseStream();
            reader = new StreamReader(stream, encoding);
            result = reader.ReadToEnd();
            if (reader != null) reader.Close();
            if (stream != null) stream.Close();
            if (rsp != null) rsp.Close();
            #endregion
            return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值