public HttpClientResponse request(String method, String path, Map<String, String> headers, String payload) {
URL url;
try {
url = new URL(baseUrl, path);
} catch (MalformedURLException e) {
throw new ElasticsearchException("Cannot parse " + path, e);
}
HttpURLConnection urlConnection;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
if (headers != null) {
for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
urlConnection.setRequestProperty(headerEntry.getKey(), headerEntry.getValue());
}
}
if (payload != null) {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
osw.write(payload);
osw.flush();
osw.close();
}
urlConnection.connect();
} catch (IOException e) {
throw new ElasticsearchException("", e);
}
int errorCode = -1;
Map<String, List<String>> respHeaders = null;
try {
errorCode = urlConnection.getResponseCode();
respHeaders = urlConnection.getHeaderFields();
InputStream inputStream = urlConnection.getInputStream();
String body = null;
try {
body = Streams.copyToString(new InputStreamReader(inputStream, Charsets.UTF_8));
} catch (IOException e1) {
throw new ElasticsearchException("problem reading error stream", e1);
}
return new HttpClientResponse(body, errorCode, respHeaders, null);
} catch (IOException e) {
InputStream errStream = urlConnection.getErrorStream();
String body = null;
if (errStream != null) {
try {
body = Streams.copyToString(new InputStreamReader(errStream, Charsets.UTF_8));
} catch (IOException e1) {
throw new ElasticsearchException("problem reading error stream", e1);
}
}
return new HttpClientResponse(body, errorCode, respHeaders, e);
} finally {
urlConnection.disconnect();