Aki.7chyan
2020-06-23 13:42
采纳率: 50%
浏览 285
已采纳

C# POST 请求传富文本时请求接口报错400

这是Postman的请求截图

图片说明

经过测试,如果newcontent内容为正常字符串时没有问题,现在要求传一个富文本内容。例如:

图片说明

场景:C#后台请求Java接口

这是C#请求代码

public string PostToPushNews(string url, NewsInfo info, NewsDetail detail)
        {
            //此处换为自己的请求url
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                { "head", "{\"newid\":\""+info.newid+"\",\"status\":\""+info.status+"\",\"md5\":\""+info.md5+"\"}" },
                { "params", "{\"newcontent\":\""+HttpUtility.UrlEncode(detail.newcontent,Encoding.UTF8)+"\",\"ywfromdate\":\""+detail.ywfromdate+"\",\"ywfrompingtai\":\""+detail.ywfrompingtai+"\",\"ywid\":\""+info.newid+"\",\"ywtitle\":\""+detail.ywtitle+"\",\"ywurl\":\"\"}" }
            };//新闻原文链接放在正文,ywurl参数不进行设置
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";

            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (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();
            }
            return result;
        }
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • wooddy1982 2020-06-23 14:28
    已采纳

    提交的时候 < 和 > 要转义成 &lt; 和 &gt;

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题