403 error when trying to get data from Reddit API

不羁岁月 提交于 2019-12-13 07:26:40

问题


I am using oAuth to authenticate my app. I managed to get a code, access_token and refresh_token. So the next step would be trying to get info about the current user.

    public async void GetCurrentUser()
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);
            var response = await client.GetAsync("https://oauth.reddit.com/api/v1/me");
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
            }
        }
    }

This is the method I am using to do that. However the response is always an 403 (Forbidden) error code. Any idea what could be wrong? The access_token is what I got when I made a request to https://oauth.reddit.com/api/v1/access_token

I think the token is correct because when I create the same request with Fiddler it works.


回答1:


ANSWER:

Fixed it by adding a custom user-agent

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, _endpointUri + "me");
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
            request.Headers.Add("User-Agent", Uri.EscapeDataString("android:com.arnvanhoutte.redder:v1.2.3 (by /u/nerdiator)"));

            var response = await client.SendAsync(request);


来源:https://stackoverflow.com/questions/39193800/403-error-when-trying-to-get-data-from-reddit-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!