個人認為百度地圖開放平臺確實很好用但就是C#的SN校驗會出現以下幾個問題 一、官方的示例代碼說的不清不楚 獲取SN函數的Uri應該使用不帶功能變數名稱的Uri 比如:最終請求地址為https://api.map.baidu.com/location/ip?ip=119.126.10.15&coor=gcj0 ...
個人認為百度地圖開放平臺確實很好用但就是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<string, string> 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<string, string> querystring_arrays) { var queryString = HttpBuildQuery(querystring_arrays); var str = UrlEncode(url + "?" + queryString + sk); return MD52(str); } } }
以上就是我被坑的經歷,希望對其他人有用~~~
最後再附帶上我的請求代碼
/// <summary> /// 返回指定IP的位置對應的百度城市代碼(利用百度地圖API /// </summary> /// <param name="IP">需要查詢的IP地址</param> /// <returns></returns> public string GetPlace(string IP) { DataTable BasicIn = Reader("SELECT Th_MapAK , Th_MapSK FROM S_Inf"); Dictionary<string, string> P = new Dictionary<string, string>() { {"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(); }