简体   繁体   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

在此处输入图片说明

在此处输入图片说明

I am testing a REST API post, and it works well when I try it on Postman.我正在测试 REST API 帖子,当我在 Postman 上尝试时,它运行良好。 However, in some scenario (related to the posting XML data) if I post with HttpClient API, I would receive the following error:但是,在某些情况下(与发布 XML 数据相关),如果我使用 HttpClient API 发布,我会收到以下错误:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.无法从传输连接读取数据:远程主机强行关闭了现有连接。

But the same XML content works fine on Postman with status OK and proper response.但是相同的 XML 内容在 Postman 上运行良好,状态正常且响应正确。

What is the differences between using the C# HttpClient API and the postman testing?使用 C# HttpClient API 和 postman 测试有什么区别? How can I configure my API call to match with the behavior on postman?如何配置我的 API 调用以匹配邮递员的行为?

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();
            }
        }
    }

Thanks for Nard's comment, after comparing the header, I found the issue my client header has this: Expect: 100-continue感谢 Nard 的评论,在比较标题后,我发现我的客户端标题有这个问题:Expect: 100-continue

While postman doesn't has.虽然邮递员没有。

Once I removed this by using the ServicePointManager:一旦我使用 ServicePointManager 删除了它:

ServicePointManager.Expect100Continue = false;

Everything seems fine now.现在一切似乎都很好。 Thanks all the input!感谢所有的投入!

My gut tells me it's something simple.我的直觉告诉我这很简单。 First, we know the API works, so I'm thinking it's down to how you are using the HttpClient.首先,我们知道 API 有效,所以我认为这取决于您如何使用 HttpClient。

First things first, try as suggested by this SO answer , creating it as a singleton and drop the using statement altogether since the consensus is that HttpClient doesn't need to be disposed:首先,按照this SO answer的建议尝试,将其创建为单例并完全删除 using 语句,因为共识是不需要处理 HttpClient :

    private static readonly HttpClient HttpClient = new HttpClient();

I would think it would be either there or an issue with your content encoding line that is causing issues with the API.我认为它要么存在,要么是您的内容编码行出现问题导致 API 出现问题。 Is there something you are missing that it doesn't like, I bet there is a difference in the requests in Postman vs here.是否有您遗漏的不喜欢的东西,我敢打赌 Postman 与此处的请求有所不同。 Maybe try sending it as JSON ala:也许尝试将其作为 JSON ala 发送:

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

Maybe the header from Postman vs yours will show something missing, I think the real answer will be there.也许 Postman vs yours 的标题会显示缺失的东西,我认为真正的答案会在那里。 Have fiddler running in the background, send it via Postman, check it, then run your code and recheck.让 fiddler 在后台运行,通过 Postman 发送,检查它,然后运行你的代码并重新检查。 Pay close attention to all the attribute tags on the header from Postman, the API works so something is missing.密切注意 Postman 标头上的所有属性标签,API 工作正常,因此缺少某些东西。 Fiddler will tell you. Fiddler 会告诉你的。

I was struggling with this for 2 days when I stumbled over Fiddler which lets you record the traffic to the service.当我偶然发现 Fiddler 时,我为此苦苦挣扎了 2 天,它可以让您记录服务的流量。 After comparing the calls I saw that I had missed a header in my code.比较调用后,我发现我的代码中遗漏了一个标题。

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

相关问题 HttpClient 后调用适用于邮递员,但不适用于 C# - HttpClient post call works on postman but not C# Http post 在 Postman 中有效,但在带有 HttpClient 的 C# 中无效 - Http post works in Postman but not in C# with HttpClient 无法使用 C# HttpClient 上传文件,Postman 工作正常 - Cannot Upload File using C# HttpClient, Postman works OK c# - HttpClient InternalServerError 500 - 适用于邮递员,但不适用于代码 - c# - HttpClient InternalServerError 500 - Works in postman, but not in code HttpClient post 在 C# 中返回错误的请求,在邮递员中工作 - HttpClient post returns bad request in c#, works in postman 拦截C#HttpClient GetAsync - Intercept C# HttpClient GetAsync 将工作邮递员请求转换为 C# (HttpClient) - Convert Working Postman Request to C# (HttpClient) 在 c# (.net core) 中使用 httpclient 时无法建立 SSL 连接,但可以在 Postman 和浏览器中使用 - The SSL connection could not be established when using httpclient in c# (.net core) but works in Postman and Browser 获取服务器错误 500,“内部服务器错误”,但在 Postman 上工作正常,在 c# 中使用 httpclient - getting server error 500, 'Internal Server Error', but works fine on Postman, using httpclient in c# Call 在 Postman 中有效,但在 C# 中无效 - Call works in Postman but not in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM