最新要闻

广告

手机

光庭信息跌4.57% 2021上市超募11亿2022扣非降74% 时快讯

光庭信息跌4.57% 2021上市超募11亿2022扣非降74% 时快讯

搜狐汽车全球快讯 | 大众汽车最新专利曝光:仪表支持拆卸 可用手机、平板替代-环球关注

搜狐汽车全球快讯 | 大众汽车最新专利曝光:仪表支持拆卸 可用手机、平板替代-环球关注

家电

环球今头条!C#百度地图开放平台211sn校验失败解决方法

来源:博客园

个人认为百度地图开放平台确实很好用但就是C#的SN校验会出现以下几个问题


(资料图片仅供参考)

一、官方的示例代码说的不清不楚

获取SN函数的Uri应该使用不带域名的Uri

比如:最终请求地址为https://api.map.baidu.com/location/ip?ip=119.126.10.15&coor=gcj02&ak=123456&sn=654321时AKSNCaculater.CaculateAKSN中的uri参数应该使用https://api.map.baidu.com/location/ip?ip=119.126.10.15&coor=gcj02&ak=123456&sn=654321,而不可以是https://aspi.map.baidu.com/location/ip?coor=gcj02&ip=119.126.10.15&ak=123456&sn=654321

获取SN的时候参数的顺序是怎么样的,发送请求的时候参数的顺序就必须是怎么样

比如:获取SN的时候参数顺序是ip=119.126.10.15&coor=gcj02&ak=123456,那么最终请求地址就应该是https://api.map.baidu.com/location/ip?ip=119.126.10.15&coor=gcj02&ak=123456&sn=654321,而不可以是https://aspi.map.baidu.com/location/ip?coor=gcj02&ip=119.126.10.15&ak=123456&sn=654321

无论如何SN必须在最终请求地址的最后!

比如以上情况下:https://api.map.baidu.com/location/ip?ip=119.126.10.15&coor=gcj02&sn=654321&ak=123456就是一个错误的地址

二、官方MD5加密是错的!

这一个真是把我害惨了,折腾了半天终于发现正确代码(我也是copy别人的,但不管怎么说,官方的MD5加密代码确实是错的)

正确的加密过程如下

public static string MD52(string password)        {            try            {                System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.MD5.Create();                byte[] hash_out = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));                 var md5_str = BitConverter.ToString(hash_out).Replace("-", "");                return md5_str.ToLower();             }            catch            {                 throw;            }        }

完整类如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace SATPlatform{     public class AKSNCaculater    {        public static string MD52(string password)        {            try            {                System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.MD5.Create();                byte[] hash_out = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));                 var md5_str = BitConverter.ToString(hash_out).Replace("-", "");                return md5_str.ToLower();             }            catch            {                 throw;            }        }         public static string MD5(string password)        {            byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(password);            try            {                System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;                cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();                byte[] hash = cryptHandler.ComputeHash(textBytes);                string ret = "";                foreach (byte a in hash)                {                    ret += a.ToString("x");                }                return ret;            }            catch            {                throw;            }        }         public static string UrlEncode(string str)        {            str = System.Web.HttpUtility.UrlEncode(str);            byte[] buf = Encoding.ASCII.GetBytes(str);//等同于Encoding.ASCII.GetBytes(str)            for (int i = 0; i < buf.Length; i++)                if (buf[i] == "%")                {                    if (buf[i + 1] >= "a") buf[i + 1] -= 32;                    if (buf[i + 2] >= "a") buf[i + 2] -= 32;                    i += 2;                }            return Encoding.ASCII.GetString(buf);//同上,等同于Encoding.ASCII.GetString(buf)        }         public static string HttpBuildQuery(IDictionary querystring_arrays)        {             StringBuilder sb = new StringBuilder();            foreach (var item in querystring_arrays)            {                sb.Append(UrlEncode(item.Key));                sb.Append("=");                sb.Append(UrlEncode(item.Value));                sb.Append("&");            }            sb.Remove(sb.Length - 1, 1);            return sb.ToString();        }         public static string CaculateAKSN(string ak, string sk, string url, IDictionary querystring_arrays)        {            var queryString = HttpBuildQuery(querystring_arrays);             var str = UrlEncode(url + "?" + queryString + sk);             return MD52(str);        }    }}

以上就是我被坑的经历,希望对其他人有用~~~

最后再附带上我的请求代码

///         /// 返回指定IP的位置对应的百度城市代码(利用百度地图API        ///         /// 需要查询的IP地址        ///         public string GetPlace(string IP)        {            DataTable BasicIn = Reader("SELECT Th_MapAK , Th_MapSK FROM S_Inf");            Dictionary P = new Dictionary()            {                {"ip",IP },                {"coor","gcj02" },                {"ak",BasicIn.Rows[0]["Th_MapAK"].ToString() }                //{"address","百度大厦" },                //{"output","json" },                //{"ak","yourak" }            };            string GetSN = AKSNCaculater.CaculateAKSN(BasicIn.Rows[0]["Th_MapAK"].ToString(), BasicIn.Rows[0]["Th_MapSK"].ToString(), "/location/ip", P);            //string GetSN = AKSNCaculater.CaculateAKSN("yourak", "yoursk", "/geocoder/v2/", P);            HttpWebRequest NewRequest = (HttpWebRequest)WebRequest.Create("https://api.map.baidu.com/location/ip?" + AKSNCaculater.HttpBuildQuery(P) + "&sn=" + GetSN);            NewRequest.Headers.Add("charset", "utf-8");            NewRequest.Method = "GET";            NewRequest.ContentType = "application/json";            NewRequest.UserAgent = "Windows KeHuDuan";            NewRequest.Timeout = 5000;//设置超时时间            HttpWebResponse Response = (HttpWebResponse)NewRequest.GetResponse();            Stream ResponseStream = Response.GetResponseStream();            StreamReader ResponseStreamReader = new StreamReader(ResponseStream);            string Res = ResponseStreamReader.ReadToEnd();            ResponseStreamReader.Close();            ResponseStream.Close();            JObject ResJ = new JObject();            try            { ResJ = JObject.Parse(Res); }            catch (Exception)            { GiveErr(ErrCode.ThirdPartyError); }            if (ResJ["status"].ToString() != "0")                GiveErr(ErrCode.ThirdPartyError);            return ResJ["content"]["address_detail"]["city_code"].ToString();        }

关键词: