C# C将REST调用的响应写入文本文件
我很难将rest调用中请求的内容写入txt文件 我得到一个响应,我可以将其输出到控制台,但我真的想将其写入一个文本文件。我倾向于它是一个编码问题,但我只是不知道在哪里设置或配置 我写的Messagebox和文件的内容是空的C# C将REST调用的响应写入文本文件,c#,rest,encoding,text-files,messagebox,C#,Rest,Encoding,Text Files,Messagebox,我很难将rest调用中请求的内容写入txt文件 我得到一个响应,我可以将其输出到控制台,但我真的想将其写入一个文本文件。我倾向于它是一个编码问题,但我只是不知道在哪里设置或配置 我写的Messagebox和文件的内容是空的 static void Main(string[] args) { // Create the web request HttpWebRequest request = WebRequest.Create(
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中的数据收集到一个temp var char[]或任何东西中,然后将其提供给所有三个输出。您正在调用reader.ReadToEnd以写入控制台,然后再次调用reader.ReadToEnd以获取MessageBox和文件输出。您需要将reader.ReadToEnd中的数据收集到temp-var char[]或其他任何文件中,然后将其提供给所有三个输出。您是在尝试写入服务器或本地计算机上的C:驱动器吗?正确,这只是一个纯测试。您是在尝试写入服务器或本地计算机上的C:驱动器吗?正确,这只是一个纯粹的测试。