mengms
2019-09-16 23:09
采纳率: 100%
浏览 1.1k

C# HttpWebResponse如何获取response body的HEX格式的数据?

        public static string Post(string url, string content)
        {
            string result = "";
            #region 添加Post 参数
            byte[] data = Encoding.UTF8.GetBytes(content);
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.KeepAlive = false;
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = data.Length;

                Stream reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();

                #endregion

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    req.Abort();
                }
                return result;

            }
            return "";
        }

请问这个代码如何修改得到HEX数据?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • threenewbee 2019-09-17 09:28
    已采纳

    Stream stream = resp.GetResponseStream();和后面修改为

    using (Stream stream = resp.GetResponseStream())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        Byte[] buffer = new Byte[1024];
                        int current = 0;
                        while ((current = stream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            ms.Write(buffer, 0, current);
                        }
                        return ms.ToArray();
                    }
                }
    

    返回值类型修改为byte[]

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题