我很难将我的请求内容从我的休息呼叫写入 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();
}
}