在Unity中测试this API的GET请求时遇到问题,出现401状态(未经授权)错误。
这是我用来通过StartCoroutine()
调用IEnumerator的代码。
IEnumerator GetTweets()
{
using (UnityWebRequest www = UnityWebRequest.Get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2"))
{
Hashtable headers = new Hashtable();
www.SetRequestHeader("Authorization", "OAuth oauth_consumer_key=\"MY_CONSUMER_KEY\"," +
"oauth_token=\"MY_TOKEN"," +
"oauth_signature_method=\"HMAC-SHA1\"," +
"oauth_timestamp=\"TIMESTAMP\"," +
"oauth_nonce=\"generated-nonce\"," +
"oauth_version=\"1.0\"," +
"oauth_signature=\"MY_SIGNATURE\"");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.responseCode);
Debug.Log(www.error);
}
else
{
// Show results as text
Debug.Log(www.downloadHandler.text);
Response tr = Response.CreateFromJSON(www.downloadHandler.text);
int index = Random.Range(0, tr.statuses.Length - 1);
Debug.Log("title is: " + tr.statuses[index].text);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
}
}
}
有趣的事实是:
-当我更改https://api.twitter.com/1.1/search/tweets.json?q=nasa
中的url时,我完全没有错误!
-当我使用"..statuses/user_timeline.."
api时在邮递员中,一切正常。
外面有人可以帮助我吗? (:祝你愉快!