Bry*_*ton 1 c# rest encoding messagebox text-files
我很难将我的休息调用中的请求内容写入 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();
}
}
Run Code Online (Sandbox Code Playgroud)
您正在调用reader.ReadToEnd()写入控制台,然后reader.ReadToEnd()再次调用MessageBox 和文件输出。您需要将数据从reader.ReadToEnd()临时变量(char[]或其他)中收集,然后将其提供给所有三个输出。