问题描述
我正在测试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:
但是相同的XML内容在邮递员的状态为OK且响应正确。
But the same XML content works fine on Postman with status OK and proper response.
使用C#HttpClient API和邮递员测试之间有什么区别?如何配置我的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 = @"https://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的评论,比较标题后,我发现我的客户标题有以下问题:
期望: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和邮递员测试之间的区别?客户端调用适用于邮递员,但不适用于C#httpClient getAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!