Skip to main content
 首页 » 编程设计

C# 将 REST 调用的响应写入文本文件

2024年02月20日12Terrylee

我很难将我的 rest 调用的请求内容写入 txt 文件。

我得到一个响应,我可以将它输出到控制台,但我真的很想将它写入一个文本文件。我倾向于它是一个编码问题,但我只是不确定在哪里设置或配置它。

我写的Messagebox和文件内容都是空的。

static void Main(string[] args) 
        { 
 
            // Create the web request   
            HttpWebRequest request = WebRequest.Create("http://finance.yahoo.com/q/ecn") as HttpWebRequest; 
 
            // Set type to POST   
            request.Method = "POST"; 
            request.ContentType = "application/x-www-form-urlencoded"; 
 
            string query = "?s=PVSW"; 
 
            StringBuilder data = new StringBuilder(); 
            data.Append("&query=" + HttpUtility.UrlEncode(query)); 
 
            System.Windows.Forms.MessageBox.Show("Data = " + data.ToString()); 
 
            // Create a byte array of the data we want to send   
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); 
 
            // Set the content length in the request headers   
            request.ContentLength = byteData.Length; 
 
            // Write data   
            using (Stream postStream = request.GetRequestStream()) 
            { 
                postStream.Write(byteData, 0, byteData.Length); 
            } 
 
            // Get response   
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
            { 
                // Get the response stream   
                StreamReader reader = new StreamReader(response.GetResponseStream()); 
 
                // Console application output   
                Console.WriteLine(reader.ReadToEnd()); 
                System.Windows.Forms.MessageBox.Show(reader.ReadToEnd()); 
 
 
                TextWriter tw = new StreamWriter("C:/Response.txt"); 
 
                // write a line of text to the file 
                tw.WriteLine(reader.ReadToEnd()); 
 
                // close the stream 
                tw.Close(); 
 
            } 
 
        }  

请您参考如下方法:

您正在调用 reader.ReadToEnd() 以写入控制台,然后再次调用 reader.ReadToEnd() 以获取 MessageBox 和文件输出。您需要从 reader.ReadToEnd() 收集数据到临时变量(char[] 或其他),然后将其提供给所有三个输出。