【问题标题】:Why does this request works using HttpWebRequest but not with RestSharp?为什么这个请求可以使用 HttpWebRequest 而不是 RestSharp?
【发布时间】:2019-10-29 22:20:55
【问题描述】:

我正在使用一个 API,它要求正文请求中包含 XML。首先,我通过 Postman 使用了 api 并且它起作用了,然后我使用 Postman 的工具将请求转换为 RestCharp C# 代码,然后使用该代码,我收到的响应与 postman 不同。之后,我使用 Fiddler 通过邮递员请求生成 c# 代码,并使用 fiddler 生成的代码,我能够通过代码成功使用 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 代码中尝试了很多东西,例如添加具有不同内容类型和编码的标头,例如

     request.AddHeader("Content-Type", "text/xml;charset=utf-8");

但没有任何效果。当被 RestSharp 代码消耗时,来自 api 的响应说它出现了 NPE 错误,我认为这意味着 NullPointerException,但是由于 api 通过邮递员和 Fiddler 生成的代码工作得很好,我不认为有问题在 API 中。顺便说一句,代码中的参数体在两个代码中完全相同。

【问题讨论】:

  • body 是 RestSharp 示例中的字符串吗?我相信它可能正在尝试序列化您的原始 xml。
  • body 是一个 XDocument,我尝试将其作为 XDocument 和作为 ToString() 的字符串传递,均无效。

标签: c# postman fiddler restsharp


【解决方案1】:

请求正文似乎与 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);

【讨论】:

  • 谢谢!使用您的第一个提示更改代码后,我能够成功使用 api!
猜你喜欢
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2018-06-05
  • 2020-10-15
相关资源
最近更新 更多