Get http web request send error in c# code

Viewed 132

I am using HttpWebRequest to get the response back and save stream as json document on to my drive. When I test via Postman all works fine but when I run the below C# code I get error.

C#:

            string url = "https://myapi.com/api/v1/city";
            var result = "";
            string json = string.Empty;

            HttpWebRequest hwrequest = WebRequest.CreateHttp(url);
            hwrequest.Method = "GET";
            hwrequest.Accept = "application/json";
            hwrequest.Credentials = new System.Net.NetworkCredential("user", "password");

            using (var response = hwrequest.GetResponse())
            using (var stream = new StreamReader(response.GetResponseStream()))
            {
                result = stream.ReadToEnd();
            }

            JavaScriptSerializer jss = new JavaScriptSerializer
            {
                MaxJsonLength = Int32.MaxValue
            };
            json = jss.Serialize(result);
            using (StreamWriter sw = new StreamWriter(File.Create(@"C:\temp\city.json")))
            {
                sw.Write(json);
            }

Error:

The underlying connection was closed. An unexpected error occurred on send.

1 Answers

That API looks like the ones displaying the json right away instead of "sending" a response.

Can you try this instead?

You will be able to use the output already in a json format any way you like after this.

        private string apiRead()
        {
            string xml = "";
            string remoteUrl = "https://myapi.com/api/v1/city";
            WebClient myWebClient = new WebClient();

            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(webUser + ":" + webPassw)); // if you use basic authorization in base64 format
            myWebClient.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
            try
            {
                byte[] myDataBuffer = myWebClient.DownloadData(remoteUrl);
                xml = Encoding.ASCII.GetString(myDataBuffer);
            }
            catch (Exception)
            {
                xml = "";
            }
            

            return xml;
        }
Related