使用 rest 客户端应用程序发送 Web 请求,但不使用 c#

Send Web request working with rest client app, but not working with c#

我正在使用 c# webrequest 和 httpClient 向 api 发送一个 post 请求,但我总是从 api 收到一条错误消息,它说你 posted header 中的无效数据,但关键是当我使用 chrome 扩展高级休息客户端发送相同的数据时它工作正常并且我比较了两个请求没有什么不同我附上了请求和我的代码,任何人都可以帮助找出问题所在,

这是来自 rest 客户端应用程序的请求:

这是来自 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();
}

它在这里看到的主要区别是在 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();
}

看起来__RequestVerificationToken在左图中包含两个下划线,所以试试这个:

request.Headers["__RequestVerificationToken"]= Token;