mengms
mengms
采纳率100%
2019-09-16 23:09

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条回答

  • caozhy 回答这么多问题就耍赖把我的积分一笔勾销了 2年前

    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[]

    点赞 1 评论 复制链接分享