最近使用elasticsearch,通过http访问,结果报错。最后发现是因为设置http消息内容格式type设置错了。发送http请求的方法如下:
public static String httpRequest(String urlStr, String content, String requestMethod) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) ();
(true);
(requestMethod);
(false);
(1000 * 5);//5秒
(1000 * 60);//1分钟
(true);
("Content-type", "application/json");
("Authorization","esmadmin");
();
Writer writer = new BufferedWriter(new OutputStreamWriter((), "UTF-8"));
if (content != null && !"".equals(content)) {
(content);
}
();
();
InputStream in = null;
if (() >= 400) {
in = ();
} else {
in = ();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String tmp;
while ((tmp = ()) != null) {
(tmp);
}
if (in != null) {
();
}
();
();
return ();
}
报错如下:
2017-08-11 08:00:00,441 pool-97-thread-1 ERROR [:run] - Unexpected end of file from server
: Unexpected end of file from server
at (:792)
at (:647)
at (:789)
at (:647)
at .getInputStream0(:1535)
at (:1440)
at (:480)
at (:126)
at (:104)
at (:80)
at $(:511)
at (:308)
at $$301(:180)
at $(:294)
at (:1142)
at $(:617)
at (:745)
后面发现上面建立http请求的httpRequest方法中是有一句代码是关键:
("Content-type", "application/json");我之前写成 ("Content-type", "JSON");所以一直报错。
后面改成("Content-type", "application/json");就好了。
这个错误对于低版本的ES好像没问题,例如V2.1.2, V5.2.1都没问题。对于ES5.4.3有问题。应该是高版本的ES对于http请求格式加强了校验。