Echo Nest API:将用于检查速率限制的 curl 命令转换为 c#

本文关键字:curl 命令 转换 速率 API Nest 检查 用于 Echo | 更新日期: 2023-09-27 18:33:36

我正在尝试将此 curl 命令转换为 c#

curl -i 'http://developer.echonest.com/api/v4/artist/profile?api_key=[API KEY]&name=weezer'

这将返回一个响应标头,内容如下:

HTTP/1.1 200 OK
Content-Length: 135
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 62
X-RateLimit-Used: 58

我尝试了这段代码,但是当我运行它时,它会出现异常:"不允许HTTP错误405方法"。

string baseurl = "http://developer.echonest.com/api/v4/artist/profile?api_key=[API KEY]&name=weezer";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl);
request.Method = "POST";
request.Accept = "application/json";
request.UserAgent = "curl/7.37.0";
request.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
    string data = "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com";
    streamWriter.Write(data);
}
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
    text = sr.ReadToEnd();
    Console.WriteLine(text);
}

任何帮助将不胜感激。

Echo Nest API:将用于检查速率限制的 curl 命令转换为 c#

除了丹尼尔建议的更改外,我还将删除UserAgent。 之后,它看起来很像我成功使用的 C#。 这是一个稍微缩短的版本:

    string baseurl = "http://developer.echonest.com/api/v4/artist/profile?api_key=[API KEY]&name=weezer";
    var req = (HttpWebRequest) WebRequest.Create(baseurl);
    req.Method = WebRequestMethods.Http.Get;
    req.Accept = "application/json";
    using (var response = (HttpWebResponse) req.GetResponse())
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            var stream = response.GetResponseStream();
            if (stream != null)
            {
                using (var sr = new StreamReader(stream))
                {
                    responseString = sr.ReadToEnd();
                }
                var remaining = GetRateInfo(response.Headers, "X-RateLimit-Remaining");
                var used = GetRateInfo(response.Headers, "X-RateLimit-Used");
                var limit = GetRateInfo(response.Headers, "X-RateLimit-Limit");
                Trace.WriteLine($"Excedeed EchoNest Limits: remaining {remaining} - used {used} - limit {limit}");
            }
        }
        else
        {
            // Error handling
        }

和标头解析代码:

    private static int GetRateInfo(WebHeaderCollection headers, string type)
    {
        var s = headers.Get(type);
        if (s == null)
            return -1;
        int info;
        return int.TryParse(s, out info) ? info : -1;
    }