0

I been trying to use an online API that returns an a json. I am using winform application at the moment.

So far i tried

WebClient cHttp = new WebClient();
string htmlCode = cHttp.DownloadString(path);  <--------

///-----------And then this

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); <-----

Where i point the arrow to, the program doesn't crash it just hit that line and then skip all the code below it. Then my form open without running my entire code. What am i doing wrong?

Thank you

Photonic
  • 1,316
  • 19
  • 31

2 Answers2

1

Use try-catch block, and you'll see an error:

try
{
    WebClient cHttp = new WebClient();
    string htmlCode = cHttp.DownloadString(path); 
}
catch(Exception e)
{
    Debug.WriteLine(e);
}
Backs
  • 24,430
  • 5
  • 58
  • 85
  • I dont get it... the path works when i input it into a browser. So this is the error in visual studio A first chance exception of type 'System.Net.WebException' occurred in System.dll System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) at System.Net.WebClient.DownloadString(Uri address) at System.Net.WebClient.DownloadString(String address) – Photonic Aug 06 '15 at 05:29
  • 1
    @Photonic and here is your problem. You have no access and you must to pass credetials like this https://msdn.microsoft.com/en-us/library/e2w99hxh(v=vs.110).aspx (it may depends) or like this http://stackoverflow.com/questions/1680718/domain-credentials-for-a-webclient-class-dont-work – Backs Aug 06 '15 at 05:31
  • Thanks i think i got pass error (401) but would you know how to fix this next error. A first chance exception of type 'System.Net.WebException' occurred in System.dll System.Net.WebException: Too many automatic redirections were attempted. at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) at System.Net.WebClient.DownloadData(Uri address) at System.Net.WebClient.DownloadData(String address) – Photonic Aug 06 '15 at 06:11
  • If i use a webBrowser class to navigate to that path, it gives me an option box to save it as json file to drive, which i dont want, so how do it just save it into a string? – Photonic Aug 06 '15 at 06:20
  • @Photonic the problem is your path variable is not final path. You should find the end :) – Backs Aug 06 '15 at 06:25
  • Thanks for putting time and effort Photonic... Anyway i found a solution http://stackoverflow.com/questions/10164259/cannot-get-html-of-page This seems to work – Photonic Aug 06 '15 at 06:28
0

It jumps out of your method. You must catch the exception and return null object. or find the error.

Bashir Mahmoudi
  • 176
  • 1
  • 15