我正在尝试使用C#访问Yelp Fusion Api的OAuth2令牌,如文档中所述:https://www.yelp.com/developers/documentation/v3/get_started
但是,我收到错误:
找不到client_id或client_secret。确保使用应用程序application / x-www-form-urlencoded在正文中提供client_id和client_secret
以下是代码段:
<code>
string baseURL = "https://api.yelp.com/oauth2/token";
Dictionary<string, string> query = new Dictionary<string, string>();
query["grant_type"] = "client_credentials";
query["client_id"] = CONSUMER_KEY;
query["client_secret"] = CONSUMER_SECRET;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL);
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(query.ToString());
requestWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
Console.WriteLine(stream.ReadToEnd());
</code>
答案 0 :(得分:1)
根据Yelp Fusion文档here,您需要进行POST调用,参数应以application / x-www-form-urlencoded格式发送。所以上面使用的方法是不正确的。
这应该有所帮助:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(baseURL);
webRequest.Method = "POST";
webRequest.AllowAutoRedirect = true;
webRequest.Timeout = 20 * 1000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36";
//write the data to post request
String postData = "client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&grant_type=client_credentials";
byte[] buffer = Encoding.Default.GetBytes(postData);
if (buffer != null)
{
webRequest.ContentLength = buffer.Length;
webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
}
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
请注意,上面的示例将以String格式返回数据。要读取实际值,您必须序列化数据。
编辑:自2018年3月1日起,yelp fusion API的身份验证过程已更改。这不再适用。