首页 > 解决方案 > 从 c# 调用时,Yelp Fusion API v3 返回 401 Unauthorized with TOKEN_MISSING 错误

问题描述

我在 Yelp 中创建了我的应用程序,获得了我的 api 密钥,并且在执行业务搜索时 Postman 一切正常。

但是,当从 c# 进行测试时,我收到一个 401 未授权错误和一个 TOKEN_MISSING 错误,上面写着 ""{\"error\": {\"code\": \"TOKEN_MISSING\", \"description\": \"An必须提供访问令牌才能使用此端点。\"}}""。

不过,我正确地提供了我的 api 密钥,Yelp 文档说这就是我所需要的,所以我不确定问题是什么。以下是 2 个不起作用的单独 c# 代码示例(出于安全考虑,我已将实际的 api 密钥替换为):

使用 WebRequest 的示例:

var webRequest = WebRequest.Create("http://api.yelp.com/v3/businesses/search?term=Clayton+Bicycle+Center&location=5411+Clayton+Rd%2c+Clayton%2c+CA+94517%2c+US");
webRequest.Method = "GET";
webRequest.Headers.Add("Cache-Control", "no-cache");
webRequest.Headers.Add("Authorization", "Bearer <my_api_key>");
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
var stream = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
var content = stream.ReadToEnd();
Console.Write(content);

使用 RestSharp 的示例:

var client = new RestClient("http://api.yelp.com/v3/businesses/search?term=Clayton+Bicycle+Center&location=5411+Clayton+Rd%2c+Clayton%2c+CA+94517%2c+US");
var request = new RestRequest(Method.GET);
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "Bearer <my_api_key>");
var response = client.Execute(request);
Console.Write(response.Content);

我已经检查了 Fiddler 中的请求,并且两者都发送与工作 Postman 搜索相同的标头,但两者都返回 401 未经授权的错误,而 Postman 返回搜索结果。有任何想法吗?

编辑:

好吧,这很尴尬,显然我的问题是我试图通过 http 而不是 https 访问 Yelp API。一旦我更改为 https,一切都按预期工作。

标签: c#apirestsharpyelpunauthorized

解决方案


将端点更改为使用 https 而不是 http,现在可以使用。


推荐阅读