VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • 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加密代码确实是错的)

正确的加密过程如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
            }
        }

  完整类如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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 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<stringstring> 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<stringstring> querystring_arrays)
        {
            var queryString = HttpBuildQuery(querystring_arrays);
 
            var str = UrlEncode(url + "?" + queryString + sk);
 
            return MD52(str);
        }
    }
}

  



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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/// <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<stringstring> P = new Dictionary<stringstring>()
    {
        {"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();
}

  


出处:https://www.cnblogs.com/nahida/p/17526893.html


相关教程