Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Getting a 401 error while attempting to get User Profile

Yea, this is all on me. I'm doing something wrong. 

I'm attempting to use an existing library, FitbitApiLibrary, and am having issues getting the afore mention profile after authorization. I am fairly certain that the library is somehow outdated. Below is the code for making a basic web request. Assuming that I had the correct url and accessToken, what's missing from this code?

BTW: The url I'm using is: https://api.fitbit.com/1/user/2YPTKF/profile.json

Is it possible that the userID needs to be encoded? If so, how is it encoded?

Thanks.

namespace FitbitApiLibrary.Helpers
{
	internal class WebRequestHelper
	{
		internal static string GetDataRequestWebRequest(string url, string accessToken)
		{
			string result = "";
			HttpWebRequest webRequest = WebRequest.CreateHttp(url);
			webRequest.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {accessToken}");
			webRequest.ContentType = "application/x-www-form-urlencoded";
			webRequest.ProtocolVersion = HttpVersion.Version10;
			webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg";
			webRequest.Referer = "https://www.fitbit.com/";
			webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.0; rv:9.0.1) Gecko/20100101 Firefox/9.0.1";
			webRequest.Method = "GET";
			var webResponse = webRequest.GetResponse();
			var streamReader = new StreamReader(webResponse.GetResponseStream());
			result = streamReader.ReadToEnd();
			streamReader.Close();
			webResponse.Dispose();
			return result;
		}
	}
}

 

Best Answer
0 Votes
3 REPLIES 3

Many issues here but these are the ones that matter.
AccessToken is longer than 255 characters. Now stored in the DB as nvarchar(max).
Web page itself needs Async="true" in the first line if this gets converted to HttpClient()

Best Answer
0 Votes

Hi @mkbutler 

I'm not familiar with that library.   But, a 401 error typically means you don't have access to that endpoint.   I would suggest doing the following:

  • I don't think you need to following lines of code
webRequest.ProtocolVersion = HttpVersion.Version10;
webRequest.Referer = "https://www.fitbit.com/";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.0; rv:9.0.1) Gecko/20100101 Firefox/9.0.1";

Hope this helps.

Gordon

Best Answer
0 Votes

Are you saying that I am going to actually write decent code to not have this app I'm working on not crash all the time? You're kidding aren't you?

Error Handling? PAH!
Results Verification? Are you kidding?

I may be a terrible hack but I fit in here at the office. 🙂

Best Answer
0 Votes