Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Maryna Nogtieva
Maryna Nogtieva
12,005 Points

I'm getting exception The remote server returned an error: (401) Unauthorized.

When I run the program it throws me an exception : "The remote server returned an error: (401) Unauthorized." for webClient.DownloadData method. What might be the reason of this error?

this is the line where the exception is thrown: byte[] searchResult = webClient.DownloadData(string.Format(" https://api.cognitive.microsoft.com/bing/v5.0/news/search?q={0}&mkt=en-us", playerName));

I'm working with this course https://teamtreehouse.com/library/searching-for-news-headlines Here is my code from visual studio:

public static string GetNewsForPlayer(string playerName) { var webClient = new WebClient(); webClient.UseDefaultCredentials = true; byte[] searchResult = webClient.DownloadData(string.Format(" https://api.cognitive.microsoft.com/bing/v5.0/news/search?q={0}&mkt=en-us", playerName)); webClient.Headers.Add("Ocp-Apim-Subscription-Key", "d3370d54aab8448d87dd674b8fafea1b"); using (var stream = new MemoryStream(searchResult)) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } }

Steven Parker
Steven Parker
231,008 Points

It would help in understanding your issue if you were to show your code or link to a workspace snapshot (or github repo?). Also please link to the course page you're working with.

In the meatime — just a wild guess — did you use http protocol with a server that requires https?

2 Answers

Steven Parker
Steven Parker
231,008 Points

:point_right: The problem appears to be an invalid subscription key.

The full text of your error message is: "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription."

Where did you get this key? It's apparently no good, which is actually fortunate as you should not post a good one in an open forum like this.

Anyway, it appears the way to resolve your issue is to replace "d3370d54aab8448d87dd674b8fafea1b" with a valid subscription key.

Maryna Nogtieva
Maryna Nogtieva
12,005 Points

Wow, thank you for help. I got this key from Bing search API. They give 2 keys, I tried them both, but it throws me an exception. Anyways, I'll try to get the right one

Maryna Nogtieva
Maryna Nogtieva
12,005 Points

Steven Parker, the http instead of https doesn't solve the problem....