WebResponse returning 401 error in loop, but works on a case-by-case. Any ideas?
<p>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.</p>

<p>I'm editing the url for safety reasons.</p>

<pre><code>        // 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();
         }
</code></pre>

<p>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.</p>

<p>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.</p>