早上好,我正在编写一个程序,对网站进行POST webrequest(websta.me)。请求有效,但问题是响应。 我使用Charles分析了http请求,这是正常的响应:
{"meta":{"code":200},"data":{"created_time":"xs","text":"xxxx <3","from":{"username":"xxxx","profile_picture":"xxxx","id":"xxxx","full_name":"xxxx"},"id":"xxxx"},"status":"OK","called_count":x}
我的程序正在返回:
关于如何解决这个问题的任何想法?在此先感谢任何帮助:) 这是我的代码,如果它可以帮助:
byte[] bytes = ASCIIEncoding.UTF8.GetBytes("comment=+xxx&media_id=xxx");
HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("http://websta.me/api/comments/xxx);
WebHeaderCollection postHeaders = postReq.Headers;
postReq.Method = "POST";
postReq.Timeout = 10000;
postReq.Host = "websta.me";
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/35.0";
postReq.Accept = "application/json, text/javascript, */*; q=0.01";
postHeaders.Add("Accept-Language", "it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3");
postHeaders.Add("Accept-Encoding", "gzip, deflate");
postReq.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
postHeaders.Add("X-Requested-With", "XMLHttpRequest");
postReq.Referer = "http://websta.me/feed";
postReq.ContentLength = bytes.Length;
postReq.CookieContainer = cookies;
postReq.KeepAlive = true;
postHeaders.Add("Pragma", "no-cache");
postHeaders.Add("Cache-Control", "no-cache");
Stream postStream = postReq.GetRequestStream();
postStream.Write(bytes, 0, bytes.Length);
postStream.Close();
HttpWebResponse postResponse;
postResponse = (HttpWebResponse)postReq.GetResponse();
StreamReader reader = new StreamReader(postResponse.GetResponseStream());
MessageBox.Show(reader.ReadToEnd());
答案 0 :(得分:2)
您从请求中收到的结果是GZip压缩数据(前三个字节为0x1f8b08
)。
要从中获取文本,只需使用GZipStream
解压缩即可。像这样:
private byte[] Decompress(byte[] data)
{
using (GZipStream stream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress))
{
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}
然后将代码的结尾(从获得回复的地方)修改为:
postResponse = (HttpWebResponse)postReq.GetResponse();
Stream Reader = postResponse.GetResponseStream();
byte[] Data = new byte[postResponse.ContentLength];
Reader.Read(Data, 0, Data.Length);
Data = Decompress(Data);
string Result = System.Text.Encoding.UTF8.GetString(Data);
MessageBox.Show(Result);
将响应数据(被压缩)读取到字节数组中,然后在将其转换为适当的文本(我相信内容类型描述为utf-8)之前对其进行解压缩。
请注意,GZip减压程序取自http://www.dotnetperls.com/decompress(不是我的)。