0

I'm running into a situation where I'm getting a (401) not authorized response. However, when I test each item line by line, it works fine. Since it's in a loop when these errors are thrown, I believe that a connection is still open, but I'm not sure how to close it.

I'm editing the url for safety reasons.

        // build variables
        var url = "https://api.com/accounts/" + aid + "/summary";

        // authentication, contenttype, etc. per API
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        webrequest.Method = "GET";
        webrequest.ContentType = "application/json";
        webrequest.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:28.0) Gecko/20100101 Firefox/28.0";
        webrequest.Headers.Add("Authorization", userAuth);
        webrequest.KeepAlive = false;

        try
        {
            // Setup download
            WebResponse response = webrequest.GetResponse();
            Stream datastream = response.GetResponseStream();
            StreamReader sr = new StreamReader(datastream);

            // read data
            string json = sr.ReadToEnd();
            string alljson = json;

            sr.Close();
            datastream.Close();
            response.Close();
         }

aid and userAuth are variables pulled from a database. When I manually injected several and did each one at a time, they all worked just fine. However, running them through a loop doesn't seem to work beyond the first one.

I've also tried adding a webrequest.Abort() in a finally statement, with no luck. Any help appreciated. Another thing I've tried us a using statement, but still no luck.

Ray
  • 9
  • 3
  • A cookie is being create when start application. The server recognizes from the cookies that you are still connected and gives error second time you try to connect. You need to use same cookie every time you go through loop. – jdweng May 17 '16 at 22:20
  • Suggestions on how to do that? – Ray May 18 '16 at 21:19
  • See webpage : http://stackoverflow.com/questions/571964/automatic-cookie-handling-c-net-httpwebrequesthttpwebresponse – jdweng May 19 '16 at 00:47

0 Answers0