我正在使用c#webrequest和httpClient向api发送一个帖子请求但是我总是从api收到一条错误消息,说明你在标题中发布了无效数据,但重点是我发送带有chrome extension的相同数据休息客户端它工作正常,我比较了两个请求没有什么不同,我已经附加了请求和我的代码,任何人都可以帮助找出问题所在,
这是来自其他客户端应用的请求:
这是来自c#
的请求这是我的c#代码
string item = "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>" +
"<request>" +
"<Username>admin</Username>" +
"<Password>" + password + "</Password>" +
"<password_type>4</password_type>" +
"</request> ";
var request = (HttpWebRequest)WebRequest.Create("http://192.168.8.1/api/user/login");
request.Method = "POST";
request.Headers["_RequestVerificationToken"]= Token;
request.Headers["Cookie"] = Sess;
byte[] bytes = Encoding.UTF8.GetBytes(item);
request.ContentType = "application/xml;charset=UTF-8";
request.ContentLength = bytes.Length;
Stream streamreq = request.GetRequestStream();
streamreq.Write(bytes, 0, bytes.Length);
streamreq.Close();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
}
答案 0 :(得分:4)
看起来__RequestVerificationToken
在左图中包含两个下划线,所以试试这个:
request.Headers["__RequestVerificationToken"]= Token;
答案 1 :(得分:1)
它在这里看到的主要区别在于您发送的API
application/xml
但是你要发送的C#代码
application/xml;charset=UTF-8;
在您的API中,内容长度为230,在C#中,内容长度为227,3个字符更少。
现在,这可能是一个很长的过程,但字符集对每个浏览器和每种语言的工作方式都不同,因此在代码中添加charset=UTF-8
时可能会出现问题。
按如下方式发送您的请求:
string item = "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>" +
"<request>" +
"<Username>admin</Username>" +
"<Password>" + password + "</Password>" +
"<password_type>4</password_type>" +
"</request> ";
var request = (HttpWebRequest)WebRequest.Create("http://192.168.8.1/api/user/login");
request.Method = "POST";
request.Headers["_RequestVerificationToken"]= Token;
request.Headers["Cookie"] = Sess;
byte[] bytes = Encoding.UTF8.GetBytes(item);
request.ContentType = "application/xml";
request.ContentLength = bytes.Length;
Stream streamreq = request.GetRequestStream();
streamreq.Write(bytes, 0, bytes.Length);
streamreq.Close();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
}