【发布时间】:2018-03-19 10:44:33
【问题描述】:
当我尝试在 Elasticseach 中发布 Json 时收到异常:
System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).
in System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
in httpclient.Program.<Run>d__1.MoveNext() in C:\httpclient\httpclient\Program.cs:riga 17
有人可以帮我吗?
我想在索引“indexx”中添加一个文档。 我需要使用任务列表,因为我必须使用异步方法来避免应用程序变慢。
提前致谢
代码:
public static List<System.Threading.Tasks.Task> PostList = new List<System.Threading.Tasks.Task>();
static async System.Threading.Tasks.Task Run()
{
HttpClient client = new HttpClient();
string c = "{\"book\": \"Help me\"}";
var content = new StringContent(c, Encoding.UTF8, "application/json");
var response = client.PostAsync(new Uri("http://10.236.0.124:9200/indexx"), content).Result;
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return;
}
static void Main(string[] args)
{
PostList.Add(Run());
try
{
System.Threading.Tasks.Task.WaitAll(PostList.ToArray());
Console.WriteLine("WaitAll() has not thrown exceptions. THIS WAS NOT EXPECTED.");
}
catch (AggregateException e)
{
Console.WriteLine("\nThe following exceptions have been thrown by WaitAll(): (THIS WAS EXPECTED)");
for (int j = 0; j < e.InnerExceptions.Count; j++)
{
Console.WriteLine("\n---------------\n{0}", e.InnerExceptions[j].ToString());
}
}
}
解决方案:
static async System.Threading.Tasks.Task Run()
{
HttpClient client = new HttpClient();
client.Timeout = new TimeSpan(0, 0, 0, 0, 5000);
client.BaseAddress = new Uri("http://10.236.0.124:9200");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, "indexx");
request.Content = new StringContent("{\"book\": \"Help me\"}",
Encoding.UTF8,
"application/json");
await client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
}
【问题讨论】:
-
你没有在这里用异步加速任何事情。但更大的问题是您的“错误请求”。您需要检查您发送的内容是否与文档说明您需要发送的内容相符。
-
回复中是否有任何其他信息说明失败的原因?也许在 Content 或 ReasonPhrase 属性中?
-
Crowcoder -> 我已经尝试使用 Chrome 的插件“JaSON”发布相同的内容,它工作正常。简单 Ged -> 响应中没有其他信息..
-
索引 API 需要指定类型,因此请尝试将 /typename 添加到 URL 的末尾
-
sramalingam24 -> 我尝试添加类型 (10.236.0.124:9200/indexx/typee) 但它不起作用。
标签: c# elasticsearch post httpclient