繁体   English   中英

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

[英]Differences between using C# HttpClient API and the postman testing? Client call works on postman, but not C# httpClient getAsync

在此处输入图片说明

在此处输入图片说明

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

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

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

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

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

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 的评论,在比较标题后,我发现我的客户端标题有这个问题:Expect: 100-continue

虽然邮递员没有。

一旦我使用 ServicePointManager 删除了它:

ServicePointManager.Expect100Continue = false;

现在一切似乎都很好。 感谢所有的投入!

我的直觉告诉我这很简单。 首先,我们知道 API 有效,所以我认为这取决于您如何使用 HttpClient。

首先,按照this SO answer的建议尝试,将其创建为单例并完全删除 using 语句,因为共识是不需要处理 HttpClient :

    private static readonly HttpClient HttpClient = new HttpClient();

我认为它要么存在,要么是您的内容编码行出现问题导致 API 出现问题。 是否有您遗漏的不喜欢的东西,我敢打赌 Postman 与此处的请求有所不同。 也许尝试将其作为 JSON ala 发送:

     var json = JsonConvert.SerializeObject(strUCDExport.ToString());
     var content = new StringContent(json, Encoding.UTF8, Mediatype);

也许 Postman vs yours 的标题会显示缺失的东西,我认为真正的答案会在那里。 让 fiddler 在后台运行,通过 Postman 发送,检查它,然后运行你的代码并重新检查。 密切注意 Postman 标头上的所有属性标签,API 工作正常,因此缺少某些东西。 Fiddler 会告诉你的。

当我偶然发现 Fiddler 时,我为此苦苦挣扎了 2 天,它可以让您记录服务的流量。 比较调用后,我发现我的代码中遗漏了一个标题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM