Quantcast
Channel: Web API
Viewing all articles
Browse latest Browse all 4850

Make a json request to website that need authentication

$
0
0

HI

I'm newbie on c# and i'm trying to get a json string from a website that needs authentication with email and password.

string url = "https://portalqa.***.com/test.json"; -> Json String
string loginUrl = "https://portalqa.
***.com/users/sign_in"; -> Login Form

I'm doing this, but when i try make the second request i got ever 401 error(HTTP Error 401 - Unauthorized: Access is denied due to invalid credentials). Someone can help me?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
requestSec.CookieContainer = Login();

HttpWebResponse resp = (HttpWebResponse)requestSec.GetResponse();  

 protected static CookieContainer Login()
        {
            string userName = "***********";
            string password = "***********";

            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "user[email]=" + userName + "&user[password]=" + password;
            byte[] postDataBytes = encoding.GetBytes(postData);

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://portalqa.
***.com/users/sign_in");


            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ContentLength = postDataBytes.Length;
            httpWebRequest.AllowAutoRedirect = false;

            using (var stream = httpWebRequest.GetRequestStream())
            {
                stream.Write(postDataBytes, 0, postDataBytes.Length);
                stream.Close();
            }

            var cookieContainer = new CookieContainer();

            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                {
                    foreach (Cookie cookie in httpWebResponse.Cookies)
                    {
                        cookieContainer.Add(cookie);
                    }
                }
            }

            return cookieContainer;
        }
     
  


Viewing all articles
Browse latest Browse all 4850

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>