簡體   English   中英

在 c# 代碼中獲取 http web 請求發送錯誤

[英]Get http web request send error in c# code

我正在使用 HttpWebRequest 來獲取響應並將 stream 作為 json 文檔保存到我的驅動器上。 當我通過 Postman 進行測試時,一切正常,但是當我運行下面的 C# 代碼時出現錯誤。

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);
            }

錯誤:

基礎連接已關閉。 發送時發生意外錯誤。

API 看起來像立即顯示 json 而不是“發送”響應的那些。

你可以試試這個嗎?

在此之后,您將能夠以任何您喜歡的方式使用 json 格式的 output。

        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;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM