关于api:聚合数据常用快递接口代码

42次阅读

共计 7579 个字符,预计需要花费 19 分钟才能阅读完成。

聚合数据罕用快递接口
申请地址:https://www.juhe.cn/docs/api/id/43

  1. ashx 代码

 publicvoid ProcessRequest(HttpContext context)

       {

           context.Response.ContentType = "text/plain";

           string appkey ="";// 配置您申请的 appkey                         

  //1. 罕用快递查问 API           

           string url1 ="http://v.juhe.cn/exp/index";

           var parameters1 =newDictionary<string,string>();

           parameters1.Add("com","");// 须要查问的快递公司编号           

           parameters1.Add("no","");// 须要查问的订单号           

           parameters1.Add("key", appkey);// 你申请的 key           

           parameters1.Add("dtype","json");// 返回数据的格局,xml 或 json,默认 json            

           string result1 = sendPost(url1,parameters1,"get");

           JsonObject newObj1 =newJsonObject(result1);

           String errorCode1 =newObj1["error_code"].Value;

           if (errorCode1 =="0")

           {context.Response.Write(newObj1);

               return;

           }

           else

           {Console.WriteLine(newObj1["error_code"].Value + ":" + newObj1["reason"].Value);

           }

       }

 
       publicbool IsReusable

       {

           get

           {returnfalse;}

       }

       ///<summary>

       /// Http (GET/POST)

       ///</summary>

       ///<param name="url"> 申请 URL</param>

       ///<param name="parameters"> 申请参数 </param>

       ///<param name="method"> 申请办法 </param>

       ///<returns> 响应内容 </returns>

       staticstring sendPost(string url, IDictionary<string,string> parameters,string method)

       {if (method.ToLower()=="post")

           {

               HttpWebRequest req =null;

               HttpWebResponse rsp =null;

               System.IO.Stream reqStream =null;

               try

               {req = (HttpWebRequest)WebRequest.Create(url);

                   req.Method = method;

                   req.KeepAlive = false;

                   req.ProtocolVersion = HttpVersion.Version10;

                   req.Timeout = 5000;

                   req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

                   byte[] postData =Encoding.UTF8.GetBytes(BuildQuery(parameters,"utf8"));

                   reqStream =req.GetRequestStream();

                   reqStream.Write(postData,0, postData.Length);

                   rsp = (HttpWebResponse)req.GetResponse();

                   Encoding encoding =Encoding.GetEncoding(rsp.CharacterSet);

                   returnGetResponseAsString(rsp, encoding);

               }

               catch (Exception ex)

               {return ex.Message;}

               finally

               {if (reqStream !=null) reqStream.Close();

                   if (rsp !=null) rsp.Close();}

           }

           else

           {

               // 创立申请

               HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" +BuildQuery(parameters,"utf8"));

 

               //GET 申请

               request.Method = "GET";

               request.ReadWriteTimeout =5000;

               request.ContentType = "text/html;charset=UTF-8";

               HttpWebResponse response = (HttpWebResponse)request.GetResponse();

               Stream myResponseStream =response.GetResponseStream();

               StreamReader myStreamReader =newStreamReader(myResponseStream,Encoding.GetEncoding("utf-8"));

 

               // 返回内容

               string retString =myStreamReader.ReadToEnd();

               return retString;

           }

       }

 

       ///<summary>

       /// 组装一般文本申请参数。///</summary>

       ///<param name="parameters">Key-Value 模式申请参数字典 </param>

       ///<returns>URL 编码后的申请数据 </returns>

       staticstring BuildQuery(IDictionary<string,string> parameters,string encode)

       {StringBuilder postData =newStringBuilder();

           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("=");

                   if (encode =="gb2312")

                   {postData.Append(HttpUtility.UrlEncode(value,Encoding.GetEncoding("gb2312")));

                   }

                   elseif (encode =="utf8")

                   {postData.Append(HttpUtility.UrlEncode(value,Encoding.UTF8));

                   }

                   else

                   {postData.Append(value);

                   }

                   hasParam = true;

               }

           }

           returnpostData.ToString();}

 

       ///<summary>

       /// 把响应流转换为文本。///</summary>

       ///<param name="rsp"> 响应流对象 </param>

       ///<param name="encoding"> 编码方式 </param>

       ///<returns> 响应文本 </returns>

       staticstring GetResponseAsString(HttpWebResponse rsp, Encoding encoding)

       {

           System.IO.Stream stream =null;

           StreamReader reader =null;

           try

           {

               // 以字符流的形式读取 HTTP 响应

               stream =rsp.GetResponseStream();

               reader = newStreamReader(stream, encoding);

               return reader.ReadToEnd();}

           finally

           {

               // 开释资源

               if (reader !=null) reader.Close();

               if (stream !=null) stream.Close();

               if (rsp !=null) rsp.Close();}

       }
  

 2. 前台代码

<script>

       $(function () {

           $.ajax({

               type: 'post',

               url: '/GetExpress.ashx',

               data: "{ }",

               success: function (data) {alert(0);

                   alert(data);

                   alert(eval("(" + data +")").reason);

                   alert(eval("(" + data +")").result.company);

                   var obj = eval("(" + data + ")").result.list;

                   // 循环输入物流信息

                   for(var key in obj)

                   {alert(obj[key].remark);

                   }

 

               },

               error: function (XMLHttpRequest,textStatus, errorThrown) {alert(1);

                   alert(XMLHttpRequest.status);

                   alert(XMLHttpRequest.readyState);

                   alert(textStatus);

               }

           });

       })

</script>

 3. 常见问题

XMLHttpRequest.status=200 (失常响应)
XMLHttpRequest.readyState=4 (失常接管)
ajax 也会提醒一个 parseerror 的谬误.

可能的起因是返回的数据格式与你 ajax 中写的数据格式不统一,返回的是 text 格局,而你写的是 json 格局

JQuery 将文本转化成 JSON 对象须要留神的问题

在 JQuery 的许多办法中,很多办法的参数能够传入一个 JSON 对象,比方 Ajax 办法的第二个参数。怎么将文本转化成 JSON 对象,须要留神以下问题

 varcpro_id="u2261530";(window["cproStyleApi"] =window["cproStyleApi"] ||{})[cpro_id]={at:"3",rsi0:"680",rsi1:"200",pat:"6",tn:"baiduCustNativeAD",rss1:"#FFFFFF",conBW:"1",adp:"1",ptt:"0",titFF:"%E5%BE%AE%E8%BD%AF%E9%9B%85%E9%BB%91",titFS:"14",rss2:"#000000",titSU:"0",ptbg:"90",piw:"0",pih:"0",ptp:"0"}

1)$.parseJSON 办法返回的是一个字符串,而不是 JSON 对象。
2)要将字符串转化成对象,很容易想起 JS 中的 eval 办法。事实上是能够的,不过须要加上括号。如 var js=”{\”PageIndex\”:\”1\”}”;varobj=eval(“(“+js+”)”);。不过应用 eval, 是不平安的,因为其能够编译任何 js 代码。
3)下载一个 JSON 解析器,因为其只认可 JSON 文本。这样就比拟平安了。
JSON 官方网站提供了这么一个脚本。地址:http://www.JSON.org/json2.js。应用起来比较简单,引入该文件后,如:JSON.parse($(“#ctl00_ContentPlaceHolder1_hfSearch”).val().toString())。
4)应用 JSON.parse 办法或者是 $.parseJSON 办法时,留神 JSON 数据的 name 和 value 用双引号括起来,对于 $.parseJSON 办法,还要将 JSON 字符串用单引号括起来再转换,对于 JSON.parse 办法,就不用了。真 TMD 的浪费时间。留神这几个技巧,在操作 JSON 数据时,能够少走不少弯路。
————————————————
版权申明:本文为 CSDN 博主「beautifulsarah」的原创文章,遵循 CC 4.0 BY-SA 版权协定,转载请附上原文出处链接及本申明。
原文链接:https://blog.csdn.net/beautif…

正文完
 0