我正在测试 REST API 帖子,当我在 Postman 上尝试时它运行良好。但是,在某些情况下(与发布 XML 数据相关)如果我使用 HttpClient API 发布,我会收到以下错误:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
但相同的 XML 内容在 Postman 上运行良好,状态正常且响应正确。
使用C# HttpClient API和postman测试有什么区别?如何配置我的 API 调用以匹配 postman 的行为?
这里附上源码和Postman截图
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 的评论,在比较 header 后,我发现我的客户端 header 存在以下问题: 期望:100-继续
而 postman 没有。
一旦我使用 ServicePointManager 删除了它:
ServicePointManager.Expect100Continue = false;
现在一切似乎都很好。感谢所有的输入!
关于c# - 使用 C# HttpClient API 和 postman 测试的区别?客户端调用适用于 postman ,但不适用于 C# httpClient getAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41129203/