![](/img/trans.png)
[英]GET request works in HttpWebRequest,Postman . but not in HttpClient or RestSharp
[英]Why does this request works using HttpWebRequest but not with RestSharp?
我正在使用 API ,它期望在正文请求中出现 XML 。 First i consumed the api via Postman and it worked, then i used that tool of Postman to convert the request to RestCharp C# code, and then using that code the reponse that i was receiving was different compared to postman. 之后,我使用 Fiddler 使用 postman 请求生成 c# 代码,并使用提琴手生成的代码,我能够通过代码成功使用 API。 我只是想了解从 postman 生成的代码和从 Fiddler 生成的代码之间有什么区别。
这是从 Fiddler 生成的代码,它可以工作:
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("http://x.x.x.x.x");
request.Accept = "*/*";
request.KeepAlive = true;
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
这是从 Postman 生成的代码(略有改动,但仍然是从 postman 生成的代码不起作用,我认为所做的更改不会干扰结果)使用不起作用的 RestSharp:
var client = new RestClient("http://x.x.x.x.x");
client.ConfigureWebRequest((r) =>
{
r.ServicePoint.Expect100Continue = false;
r.KeepAlive = true;
});
var request = new RestRequest();
request.AddXmlBody(body);
IRestResponse response = client.Post(request);
return response;
我在 RestSharp 代码中尝试了很多东西,例如添加具有不同内容类型和编码的 header
request.AddHeader("Content-Type", "text/xml;charset=utf-8");
但没有任何效果。 当被 RestSharp 代码使用时,来自 api 的响应说它出现了 NPE 错误,我认为这意味着 NullPointerException,但是由于 api 通过 Z03D476861AFD38411A8AAZ 工作得很好,通过 Z03D476861AFD384510F2CB80 生成的问题和问题在 API 中。 顺便说一句,代码中的参数主体在两个代码中完全相同。
看起来请求正文与 API 的预期内容类型不匹配。 当内容与 API 预期的内容类型不匹配时,您可能会收到 NPE 错误。
在您的提琴手生成的代码中,您将 XML 字符串作为文本发送。
请添加以下代码:
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("undefined", "<YourXml></YourXml>", ParameterType.RequestBody);
或者
request.AddHeader("Content-Type", "application/xml");
request.AddParameter("undefined", "<YourXml></YourXml>", ParameterType.RequestBody);
代替
request.AddXmlBody(body);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.