![](/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.