HttpWebResponse 传输IDictionary<string, string>[] parameter数组

本文探讨了在处理大量中文编码数据时,通过优化HTTP请求实现一次传输多条数据的方法,并解决了实际应用中遇到的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Data;
using System.Data;
using System.Configuration;
using System.Text;
using System.Net;




namespace NewShowInfomation
{
    public partial class AddArticle : System.Web.UI.Page
    {
        DataSet ds = new DataSet();//数据源
        Data.Common _common = new Data.Common();
        int top = 0;
        int siteid = 0;
        string fid = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            top = Convert.ToInt16(Request.QueryString["number"]);
            siteid = Convert.ToInt16(Request.QueryString["SiteId"]);
            fid = Convert.ToString(Request.QueryString["fid"]);
            this.Button1.Attributes.Add("onclick", "");
            if (fid == null)
                fid = "";
            if (top > 0 && siteid > 0 && siteid <= 6)//|| string.IsNullOrWhiteSpace(fid))) 
                initdata(top, siteid, fid);


            //这句话用来给Button1添加客户端事件。
        }
        private void initdata(int top, int siteid, string fid)
        {


            GetData dba = new GetData();
            ds = dba.GetArticleList(top, siteid, fid);
            if (ArticleList != null)
            {
                ArticleList.DataSource = ds;
                ArticleList.DataBind();
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if(this.Save())
                Response.AddHeader("Refresh", "0");


        }
        private bool Save()
        {
            string ids = "";
            string url = ConfigurationManager.AppSettings["APIurl"];            
            if (ds == null || ds.Tables.Count == 0)
                return false;
            DataTable dt = this.ds.Tables[0];
           // string content = string.Empty;
            IDictionary<string, string>[] parameter = new Dictionary<string, string>[dt.Rows.Count];
            for(int i=0;i<dt.Rows.Count;i++) 
            {
                DataRow row = dt.Rows[i];
                IDictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("SiteID", siteid.ToString());
                parameters.Add("KeyName", row["name"] == DBNull.Value ? "" : Convert.ToString(row["name"]));
                parameters.Add("Content", row["con"] == DBNull.Value ? "" : Uri.EscapeDataString(row["con"].ToString()));
                //parameters.Add("Content", row["con"] == DBNull.Value ? "" : Convert.ToString(row["con"]));
                parameters.Add("catname", row["cid"] == DBNull.Value ? "" : Convert.ToString(row["cid"]));//子分类
                parameters.Add("fidname", row["fid"] == DBNull.Value ? "" : Convert.ToString(row["fid"]));//父分类
                parameters.Add("Title", row["title"] == DBNull.Value ? "" : Convert.ToString(row["title"]));
                parameters.Add("Keyword", row["keywords"] == DBNull.Value ? "" : Convert.ToString(row["keywords"]));
                parameters.Add("Descriptions", row["description"] == DBNull.Value ? "" : Uri.EscapeDataString(row["description"].ToString()));
                // parameters.Add("Descriptions", row["description"] == DBNull.Value ? "" : Convert.ToString(row["description"]));
                parameters.Add("CreatDate", row["addtime"] == DBNull.Value ? "" : Convert.ToString(row["addtime"]));
                parameters.Add("OrtherID", row["id"] == DBNull.Value ? "0" : Convert.ToString(row["id"]));
                if (ids == "")
                    ids = Convert.ToString(row["id"]);
                else
                    ids += "," + Convert.ToString(row["id"]);
                parameter[i] = parameters;
            }
            lock (this)
            {  
                Encoding encoding = Encoding.GetEncoding("utf-8");
                try
                {
                    HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(url, parameter, null, null, encoding, null);
                    // int id = row["id"] == DBNull.Value ? 0 : Convert.ToInt32(row["id"]);
                    //  bool issuccess = ["iss"] == "true" ? true : false;
                    bool issuccess = false;
                    if (response.StatusCode.ToString() == "OK")
                        issuccess = true;
                    if (ids!="" && siteid > 0)
                    {
                        GetData dba = new GetData();
                        dba.UpdateStatus(ids, siteid, issuccess);
                    }
                }
                catch (Exception ex)
                {
                    _common.WriteLog(ex.ToString());
                    return false;
                }
            }
            return true;
        }
        //asp页面注册按钮命令
        protected void Button_Command(object sender, CommandEventArgs e)
        {


        }
    }

}

因为传输数据流比较大,都是汉字编码,所以本想通过这种一次传输多条数据,结果测试一次只有传输1条数据才能通。




using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;


namespace Data
{
   public  class HttpWebResponseUtility
    {
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        /// <summary>   
        /// 创建GET方式的HTTP请求   
        /// </summary>   
        /// <param name="url">请求的URL</param>   
        /// <param name="timeout">请求的超时时间</param>   
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>   
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>   
        /// <returns></returns>   
        public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = DefaultUserAgent;
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            return request.GetResponse() as HttpWebResponse;
        }
        /// <summary>   
        /// 创建POST方式的HTTP请求   
        /// </summary>   
        /// <param name="url">请求的URL</param>   
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>   
        /// <param name="timeout">请求的超时时间</param>   
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>   
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>   
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>   
        /// <returns></returns>   
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string>[] parameter, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    throw new ArgumentNullException("url");
                }
                if (requestEncoding == null)
                {
                    throw new ArgumentNullException("requestEncoding");
                }
                HttpWebRequest request = null;
                //如果是发送HTTPS请求   
                if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";


                if (!string.IsNullOrEmpty(userAgent))
                {
                    request.UserAgent = userAgent;
                }
                else
                {
                    request.UserAgent = DefaultUserAgent;
                }


                if (timeout.HasValue)
                {
                    request.Timeout = timeout.Value;
                }
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                StringBuilder buffer = new StringBuilder();
                //如果需要POST数据   
                foreach (IDictionary<string, string> parameters in parameter)
                {
                    if (!(parameters == null))
                    {
                        int i = 0;
                        foreach (string key in parameters.Keys)
                        {
                            if (i > 0)
                            {
                                buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                            }
                            else
                            {
                                buffer.AppendFormat("{0}={1}", key, parameters[key]);
                            }
                            i++;
                        }
                    }
                    byte[] data = requestEncoding.GetBytes(buffer.ToString());
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                return request.GetResponse() as HttpWebResponse;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }


        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受   
        }   
    }
}


最近用get,居然不会解析返回的response;

解析Response:
C#语言是解析http的stream数据流获取的。

 var weatherResponse= request.GetResponse() ;
            var weatherResponse= request.GetResponse() ;
            Stream weatherStream = weatherResponse.GetResponseStream();
            //读取数据流
            StreamReader weatherStreamReader = new StreamReader(weatherStream, System.Text.Encoding.Default);
            //读取数据
           string weatherHtml = weatherStreamReader.ReadToEnd();
            weatherStreamReader.Close();
            weatherStream.Close();
            weatherResponse.Close();
            //针对不同的网站查看html源文件
            return weatherHtml;


服务端接收还是需要验证下,传输调通接口问题不大。

我前段时间写了一个python程序,用于抓取自己闲鱼页面的商品信息,但是为了避免违规,我想重新编写一个程序,用于在阿奇索后台(开发指南:接入指南 1、接入流程 【开发者操作】登录后台申请AppIds。 入口:https://open.agiso.com/#/my/application/app-list 【开发者操作】申请到AppId后,开发者可以登录后台管理AppId,这里可以查看和更换AppSecret、更改推送url、更改授权回调url等。 入口:https://open.agiso.com/#/my/application/app-list 【商家操作】授权,方法有二: 1、输入开发者提供的AppId(相当于告诉Agiso,允许这个AppId通过Agiso开放平台获取或操作商家自己的订单数据),勾选相应要授权的权限。授权后会显示一个Token,将Token复制给开发者。 入口:https://aldsIdle.agiso.com/#/open/authorize 2、开发者如果有开发自动授权,则商家可以通过访问以下页面进行授权: 入口:https://aldsIdle.agiso.com/#/authorize?appId={$请替换为要授权的开发者的appId}&state=2233 【开发者操作】开发者得到各个商家授权给的Token,并使用Token调用接口。调用接口时,需要使用AppSecret进行签名,具体签名方法参见下文。 注意:开发者与商家,也可以是同一个人。 2、获取AccessToken详解 手动模式自动模式 将你的AppId告诉您的用户,用户通过在授权页面(https://aldsIdle.agiso.com/#/open/authorize) 进行授权。用户授权完成后,会获得一个AccessToken,让您的用户把该AccessToken发给你。 AccessToken的有效期和您的用户购买Agiso软件的使用时间一致。如果您的用户续费,那么AccessToken的有效期也会延长。 3、调用接口详解 调用任何一个API都必须把AccessToken 和 ApiVersion 添加到Header ,格式为"Authorization: Bearer access_token",其中Bearer后面有一个空格。同时还需传入以下公共参数: timestamp 是 Date 时间戳,例如:1468476350。API服务端允许客户端请求最大时间误差为10分钟。 sign 是 string API输入参数签名结果,签名算法参照下面的介绍。 注意:接口调用配额,20次/秒。 4、签名算法 【对所有API请求参数(包括公共参数和业务参数,但除去sign参数和byte[]类型的参数),根据参数名称的ASCII码表的顺序排序。如:foo=1, bar=2, foo_bar=3, foobar=4排序后的顺序是bar=2, foo=1, foo_bar=3, foobar=4。 将排序好的参数名和参数值拼装在一起,根据上面的示例得到的结果为:bar2foo1foo_bar3foobar4。 把拼装好的字符串采用utf-8编码,在拼装的字符串前后加上app的secret后,使用MD5算法进行摘要,如:md5(secret+bar2foo1foo_bar3foobar4+secret); 5、Header设置示例代码 JavaC#PHP HttpPost httpPost = new org.apache.http.client.methods.HttpPost(url); httpPost.addHeader("Authorization","Bearer "+ accessToken); httpPost.addHeader("ApiVersion", "1"); 6、签名算法示例代码 JavaC#PHP Map<String, String> data = new HashMap<String, String>(); data.put("modifyTimeStart", "2016-07-13 10:44:30"); data.put("pageNo", "1"); data.put("pageSize", "20"); //timestamp 为调用Api的公共参数,详细说明参考接入指南 data.put("timestamp", '1468476350');//假设当前时间为2016/7/14 14:5:50 //对键排序 String[] keys = data.keySet().toArray(new String[0]); Arrays.sort(keys); StringBuilder query = new StringBuilder(); //头加入AppSecret ,假设AppSecret值为****************** query.append(this.getClientSecret()); for (String key : keys) { String value = data.get(key); query.append(key).append(value); } //到这query的值为******************modifyTimeStart2016-07-13 10:44:30pageNo1pageSize20timestamp1468476350 //尾加入AppSecret query.append(this.getClientSecret()); //query=******************modifyTimeStart2016-07-13 10:44:30pageNo1pageSize20timestamp1468476350****************** byte[] md5byte = encryptMD5(query.toString()); //sign 为调用Api的公共参数,详细说明参考接入指南 data.put("sign", byte2hex(md5byte)); //byte2hex(md5byte) = 935671331572EBF7F419EBB55EA28558 // Md5摘要 public byte[] encryptMD5(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md5 = MessageDigest.getInstance("MD5"); return md5.digest(data.getBytes("UTF-8")); } public String byte2hex(byte[] bytes) { StringBuilder sign = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() == 1) { sign.append("0"); } sign.append(hex.toLowerCase()); } return sign.toString(); } 7、完整调用API示例代码 以下代码以调用LogisticsDummySend(更新发货状态)为例 JavaC#PHP public String LogisticsDummySend() { string accessToken = "*************"; string appSecret = "*************"; WebRequest apiRequest = WebRequest.Create("http://gw.api.agiso.com/aldsIdle/Trade/LogisticsDummySend"); apiRequest.Method = "POST"; apiRequest.ContentType = "application/x-www-form-urlencoded"; apiRequest.Headers.Add("Authorization", "Bearer " + accessToken); apiRequest.Headers.Add("ApiVersion", "1"); //业务参数 TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); var args = new Dictionary<string,string>() { {"tids","123456789,987465123"}, 注意 tids是示例参数实际参数要以当前文档上的入参为准!!! {"timestamp",Convert.ToInt64(ts.TotalSeconds).ToString()} }; args.Add("sign", Sign(args, appSecret)); //拼装POST数据 string postData = ""; foreach (var p in args) { if (!String.IsNullOrEmpty(postData)) { postData += "&"; } string tmpStr = String.Format("{0}={1}", p.Key, HttpUtility.UrlEncode(p.Value)); postData += tmpStr; } using (var sw = new StreamWriter(apiRequest.GetRequestStream())) { sw.Write(postData); } WebResponse apiResponse = null; try { apiResponse = apiRequest.GetResponse(); } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { apiResponse = (we.Response as HttpWebResponse); } else{ //TODO:处理异常 return ""; } } using(Stream apiDataStream = apiResponse.GetResponseStream()){ using(StreamReader apiReader = new StreamReader(apiDataStream, Encoding.UTF8)){ string apiResult = apiReader.ReadToEnd(); apiReader.Close(); apiResponse.Close(); return apiResult; } } } //参数签名 public string Sign(IDictionary<string,string> args, string ClientSecret) { IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(args, StringComparer.Ordinal); string str = ""; foreach (var m in sortedParams) { str += (m.Key + m.Value); } //头尾加入AppSecret str = ClientSecret + str + ClientSecret; var encodeStr = MD5Encrypt(str); return encodeStr; } //Md5摘要 public static string MD5Encrypt(string text) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] fromData = System.Text.Encoding.UTF8.GetBytes(text); byte[] targetData = md5.ComputeHash(fromData); string byte2String = null; for (int i = 0; i < targetData.Length; i++) { byte2String += targetData[i].ToString("x2"); } return byte2String; })作为API接入商家后台,我想要获取我自己的商品数据:(# helps.py(仅仅作为功能参考,可以根据实际编写需要改写) import os def display_help(): """显示帮助信息""" print(""" 商品信息抓取工具 v1.0 ========================== 使用方法: python main.py [选项] 选项: -u, --url URL 商品URL -o, --output PATH 输出文件路径(.docx) -f, --file FILE 批量任务文件路径 -t, --threads N 并发线程数(默认:2) -d, --debug 启用调试模式 -v, --verbose 显示详细输出 -h, --help 显示帮助信息 批量任务文件格式: URL | 输出文件名称 以#开头的行默认为注释,将不会进行任何的处理 示例: https://2.taobao.com/item?id=123 | item1.docx https://2.taobao.com/item?id=456 | item2.docx 输出文件: 1. Word文档(.docx) - 包含商品标题、描述和图片 2. Excel报告(.xlsx) - 包含word文档标题和元数据(价格,商品标题等) 日志文件: xianyu_scraper.log - 包含详细运行日志 依赖库: pip~=25.1.1 requests==2.32.4 beautifulsoup4==4.12.3 python-docx==1.1.0 pandas==2.3.1 openpyxl==3.1.5 fake-useragent==2.2.0 htmldocx==0.0.6 pillow==11.3.0 selenium==4.34.2 webdriver-manager==4.0.2 tqdm==4.67.1(进度条) """) def show_banner(): """显示程序横幅""" print(r""" 商品信息抓取工具 v1.0 ============================================================================== """),现在请为我编写程序,并且给我一个详细的接入阿奇索后台的步骤
最新发布
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值