开发者社区 问答 正文

在阿里云 OpenAPI用php怎么读取到里面的数据?

在阿里云 OpenAPI用php怎么读取到里面的数据?代码:string accessKeyId = "xxxx"; string accessKeySecret = "xxxx"; string project = "xxx"; string endpoint = "xxx";

    // 构建查询SQL语句
    string sql = "SELECT * FROM aliyun_dahai_dw.dwd_web WHERE dt='{date}' AND res_type IN {resType}";

    // 替换占位符
    string querySql = sql.Replace("{date}", "2023-06-11")
                        .Replace("{resType}", "(1, 2, 3)");

    // 构建HTTP请求的参数
    string method = "POST";
    string apiPath = $"/projects/{project}/sql";
    string url = endpoint + apiPath;
    string date = DateTime.UtcNow.ToString("r");
    string contentMD5 = string.Empty;
    string contentType = "application/x-www-form-urlencoded";

    // 构建规范化URI
    string canonicalURI = apiPath;

    // 构建HTTP请求正文
    string requestBody = $"q={Uri.EscapeDataString(querySql)}";

    // 计算签名
    string signature = ComputeSignature(accessKeySecret, method, contentMD5, contentType, date, canonicalURI);

    // 发起HTTP请求
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("Date", date);
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("ODPS", $"{accessKeyId}:{signature}");

        var content = new StringContent(requestBody, Encoding.UTF8, contentType);
        var response = await httpClient.PostAsync(url, content);
        var responseBody = await response.Content.ReadAsStringAsync();

        Console.WriteLine(responseBody);
    }
}

static string ComputeSignature(string accessKeySecret, string method, string contentMD5, string contentType, string date, string canonicalURI)
{

    string stringToSign = $"{method}\n{contentMD5}\n{contentType}\n{date}\n{canonicalURI}";

    using (var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(accessKeySecret)))
    {
        var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
        return Convert.ToBase64String(hashBytes);
    }
}提示内容

SignatureNotMatch 6486C711B08E597E3F2038D0 *.aliyun.com

展开
收起
三分钟热度的鱼 2023-06-23 18:00:24 107 分享 版权
1 条回答
写回答
取消 提交回答
  • 这是MaxCompute制作的PHP连接MaxCompute的框架,你可以基于它二次优化,https://github.com/aliyun-beta/aliyun-odps-php-sdk 此回答整理自钉群“阿里云 OpenAPI SDK 自签名服务群”

    2023-06-23 18:03:49
    赞同 展开评论