gpt4 book ai didi

c# - C#HttpClient.PostAsJsonAsync()失败,即使通过PostMan发出的请求是完全相同的请求

转载 作者:行者123 更新时间:2023-12-03 01:31:03 45 4
gpt4 key购买 nike

我在这里以及在the Elastic discussion forum上都发现了类似的问题,但不幸的是,所有答案都无济于事。

我目前正在使用ElasticSearch 7.0

我想向我的ElasticSearch服务器发出批量请求。我的JSON文件包含的信息看起来像这样:

{ "index": { "_index": "website", "_id": "link1" }}
{ "label": "Link1" }

每行以 LF换行符结尾,并且在文档末尾还有一个额外的 LF换行符。

在C#中,这是我对批量数据发出POST请求的方式:
HttpResponseMessage response = await httpClient.PostAsJsonAsync($"http://127.0.0.1:9200/website/_bulk", jsonDocumentContents);
但是我仍然看到此错误消息:
{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"The bulk request must be terminated by a newline [\\n]"}],"type":"illegal_argument_exception","reason":"The bulk request must be terminated by a newline [\\n]"},"status":400}
如何解决此错误?

更新:

关于如何将JSON文档内容读取到 jsonDocumentContents变量中的简短说明:JSON文档存储在一个压缩文件夹中,因此要获取它,需要解压缩:
ZipArchive archive = new ZipArchive(zippedFolderStream);
foreach (ZipArchiveEntry entry in archive.Entries)
{
string jsonDocumentContents = new StreamReader(entry.Open()).ReadToEnd();
HttpResponseMessage response = await httpClient.PostAsJsonAsync($"http://127.0.0.1:9200/website/_bulk", jsonDocumentContents);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}

更新:

我只是使用PostMan发出了一个内容完全相同的批量请求,请求成功。但是,当我使用 httpClient.PostAsJsonAsync(...)在C#中进行相同的批量请求时,错误消息仍然存在。

最佳答案

我通过将代码更改为以下内容来使其工作:

ZipArchive archive = new ZipArchive(zippedFolderStream);
foreach (ZipArchiveEntry entry in archive.Entries)
{
string jsonDocumentContents = new StreamReader(entry.Open()).ReadToEnd();
StringContent content = new StringContent(jsonDocumentContents, Encoding.ASCII, mediaType: "application/json");
HttpResponseMessage response = await httpClient.PostAsync($"http://127.0.0.1:9200/website/_bulk", content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}

请注意,我使用的是 HttpClient.PostAsync()而不是 HttpClient.PostAsJsonAsync(),其 StringContent实例将 "application/json"指定为其媒体类型。

我查看了 source code中的 HttpClient,发现每次调用 JsonMediaTypeFormatter时都会创建一个新的 HttpClient.PostAsJsonAsync实例。

由于我通过PostMan发出 POST请求成功后,该问题必须由 PostAsJsonAsync()的实现方式引起。我怀疑但尚未验证,问题是由于 JsonMediaTypeFormatter类中的默认属性所致。

为了避免该问题,我决定将 Http.PostAsync()与正确配置的 StringContent实例一起使用。

瞧,我现在可以使用C#将批量请求发送到我的ElasticSearch服务器。

关于c# - C#HttpClient.PostAsJsonAsync()失败,即使通过PostMan发出的请求是完全相同的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55921277/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com