获取Google API的签名

时间:2019-02-03 13:36:46

标签: c# google-api google-street-view

我正在尝试使用Google Streetview静态API获取大量的街景图像。我有一个有效的API密钥和URL签名密钥,但是在对签名进行编码时遇到了麻烦。无论我尝试了什么,我都会得到错误的签名,并且该URL不起作用。任何帮助将不胜感激。

这是我所做的(Encode方法不是我的):

from scipy.stats import entropy
import numpy as np

matrix = np.random.randint(low=1,high=5,size=(2,3,4)) #how if size is (200,50,1000)
entropy_matrix=np.zeros((matrix.shape[0],matrix.shape[1]))
for i in range(matrix.shape[0]):
    normalized = np.array([float(k)/np.sum(j) for j in matrix[i] for k in j]).reshape(matrix.shape[1],matrix.shape[2])
    entropy_matrix[i] = np.array([entropy(m) for m in normalized])

对于getSignature使用_而不是/的原因是因为here表示需要替换它。我已经尝试过使用/,但是它不起作用。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

编辑: 我已经在Google网站上找到了解决方案:

static void Main(string[] args)
    {
        Process.Start(GenerateURL(0, 0, "-26.235859", "28.077619", 500, 500, 90));

        Console.ReadLine();
    }

    public static string GenerateURL(double heading, double pitch, string locationLat, string locationLong, int resX, int resY, int fov)
    {
        return Sign("https://maps.googleapis.com/maps/api/streetview?size=" + resX + "x" + resY + "&location=" + locationLat + "," + locationLong + "&heading=" + heading + "&pitch=" + pitch + "&fov=" + fov + "&key=" + apiKey, signingKey);
    }

    public static string Sign(string url, string keyString)
    {
        ASCIIEncoding encoding = new ASCIIEncoding();

        // converting key to bytes will throw an exception, need to replace '-' and '_' characters first.
        string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/");
        byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey);

        Uri uri = new Uri(url);
        byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query);

        // compute the hash
        HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes);
        byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes);

        // convert the bytes to string and make url-safe by replacing '+' and '/' characters
        string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");

        // Add the signature to the existing URI.
        return uri.Scheme + "://" + uri.Host + uri.LocalPath + uri.Query + "&signature=" + signature;
    }