Search code examples
c#httpwebrequest

Getting the response of an instagram url


I am trying to integrate a third party application. The procedure is as follows:

  1. I have the url of the third party (login required)
  2. I have to paste this in the browser. The result of this will be an url in the browser.

For example: the url stands like this:

  1. https://api.instagram.com/oauth/authorize?client_id=157c0c51ef58435893a50e0430b5f53b&redirect_uri=http://www.hashgurus.com/redirect.aspx&response_type=code&scope=likes+basic+comments+relationships

  2. Now when I paste this url in the browser (login required, once logged in cookie is set) it redirects to another url.

Example: hashgurus.com/redirectd.aspx?code=abcdedf. The output of this url is a string.

Now I want to programatically emulate this in console application. My code:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(link);

WebResponse webresponse =  myReq.GetResponse();
StreamReader sr = new StreamReader(webresponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();

But the variable result holds some other html (the login page). Instead I expected the response of this url hashgurus.com/redirectd.aspx?code=abcdedf.

When i do everything manually in the browser, everything happens smoothly because the cookie is set. but programtically it doesnot.


Solution

  • You receiving different html source code, because of automatic redirections done by HttpWebRequest. You need first disable auto redirection. It can be done using following code:

    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(link);
    myReq.AllowAutoRedirect = false;
    

    Documentation

    After that, follow all steps provided by api. For better understanding of whole path use sniffing tools like Fiddler.