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;

}

回答

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

以上是 C# POST 请求传富文本时请求接口报错400 的全部内容, 来源链接: utcz.com/a/27409.html

回到顶部