使用 C# HttpClient API 和 postman 测试的区别?客户端调用适用于邮递员,但不适用于 C# httpClient getAsync

编程入门 行业动态 更新时间:2024-10-26 20:22:58
本文介绍了使用 C# HttpClient API 和 postman 测试的区别?客户端调用适用于邮递员,但不适用于 C# httpClient getAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在测试一个 REST API 帖子,当我在 Postman 上试用它时效果很好.但是,在某些情况下(与发布 XML 数据相关),如果我使用 HttpClient API 发布,我会收到以下错误:

I am testing a REST API post, and it works well when I try it on Postman. However, in some scenario (related to the posting XML data) if I post with HttpClient API, I would receive the following error:

无法从传输连接读取数据:现有连接被远程主机强行关闭.

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

但相同的 XML 内容在 Postman 上运行良好,状态正常且响应正确.

But the same XML content works fine on Postman with status OK and proper response.

使用 C# HttpClient API 和 postman 测试有什么区别?如何配置我的 API 调用以匹配邮递员的行为?

What is the differences between using the C# HttpClient API and the postman testing? How can I configure my API call to match with the behavior on postman?

这里附上源代码,和邮递员截图

Here I attached the source code, and the Postman screenshot

public void createLoan() { string baseCreateLoanUrl = @"serverhost/create?key="; var strUCDExport = XDocument.Load(@"C:CreateLoan_testcase.xml"); using (var client = new HttpClient()) { var content = new StringContent(strUCDExport.ToString(), Encoding.UTF8, Mediatype); string createLoanApi = string.Concat(baseCreateLoanUrl, APIKey); try { var response = client.PostAsync(createLoanApi, content).Result; } catch (Exception ex) { MessageBox.Show("Error Happened here..."); throw; } if (response.IsSuccessStatusCode) { // Access variables from the returned JSON object string responseString = response.Content.ReadAsStringAsync().Result; JObject jObj = JObject.Parse(responseString); if (jObj.SelectToken("failure") == null) { // First get the authToken string LoanID = jObj["loanStatus"]["id"].ToString(); MessageBox.Show("Loan ID: " + LoanID); } else { string getTokenErrorMsg = string.Empty; JArray errorOjbs = (JArray) jObj["failure"]["errors"]; foreach (var errorObj in errorOjbs) { getTokenErrorMsg += errorObj["message"].ToString() + Environment.NewLine; } getTokenErrorMsg.Dump(); } } }

推荐答案

感谢Nard的评论,对比了header后发现我的client header有这个问题:期望:100-继续

Thanks for Nard's comment, after comparing the header, I found the issue my client header has this: Expect: 100-continue

而邮递员没有.

一旦我使用 ServicePointManager 删除了它:

Once I removed this by using the ServicePointManager:

ServicePointManager.Expect100Continue = false;

现在一切似乎都很好.谢谢大家的意见!

Everything seems fine now. Thanks all the input!

更多推荐

使用 C# HttpClient API 和 postman 测试的区别?客户端调用适用于邮递员,但不适用于 C# httpClient getAsync

本文发布于:2023-10-29 13:19:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539798.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:适用于   邮递员   但不   客户端   区别

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!