elastic / elasticsearch-metrics-reporter-java

Metrics reporter, which reports to elasticsearch
Apache License 2.0
231 stars 103 forks source link

Exception when closing connection on Android #25

Closed glureau closed 8 years ago

glureau commented 8 years ago

Original code:

private void closeConnection(HttpURLConnection connection) throws IOException {
        connection.getOutputStream().close();
        connection.disconnect();

        // we have to call this, otherwise out HTTP data does not get send, even though close()/disconnect was called
        // Ceterum censeo HttpUrlConnection esse delendam
        if (connection.getResponseCode() != 200) {
            LOGGER.error("Reporting returned code {} {}: {}", connection.getResponseCode(), connection.getResponseMessage());
        }
    }

Disclaimer Android: I know that this plugin is not designed for Android, but it's almost working so... In the ElasticsearchReporter.closeConnection(HttpURLConnection), if you call getResponseCode after the disconnect, it will throw a IOException (Socket closed). If you swap these blocks, it works well on Java and Android.

Pure Java: Documentation: HttpURLConnection#Disconnect : Indicates that other requests to the server are unlikely in the near future.

So if we want to use the getResponseCode() to ensure the data is sent, we should probably call the disconnect method after, correct?

glureau commented 8 years ago

Swapping the 2 lines are simply not working on standard JVM, so a bit tricky to have something working everywhere... I forked my solution here for Android guys who want to try: https://github.com/Ksubaka/elasticsearch-metrics-reporter-android