我正在尝试使用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>
最佳答案
根据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融合API的身份验证过程已更改。这不再适用。
关于c# - 如何使用C#访问Yelp Fusion Api的OAuth2 token ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43554575/