[英]Simple http web post request not working properly from c# code, whereas same content from REST client is working fine
[英]Send Web request working with rest client app, but not working with c#
我正在通过c#webrequest和httpClient向api发送一个帖子请求,但我总是从api收到一条错误消息,说明你在标题中发布了无效数据,但重点是我用chrome扩展高级休息客户端发送相同的数据工作得很好,我比较了两个请求没有什么不同,我已经附加了请求和我的代码,任何人都可以帮助找出问题所在,
这是来自其他客户端应用程序的请求:
这是来自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();
}
看起来__RequestVerificationToken
在__RequestVerificationToken
包含两个下划线,所以试试这个:
request.Headers["__RequestVerificationToken"]= Token;
它在这里看到的主要区别在于您发送的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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.