Example usage for java.net HttpURLConnection disconnect

List of usage examples for java.net HttpURLConnection disconnect

Introduction

In this page you can find the example usage for java.net HttpURLConnection disconnect.

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:org.elasticsearch.metrics.ElasticsearchReporter.java

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());
    }//from w  ww.j a  v  a 2 s  .co  m
}

From source file:co.cask.cdap.gateway.handlers.StreamHandlerTest.java

@Test
public void testStreamCreate() throws Exception {
    // Try to get info on a non-existent stream
    HttpURLConnection urlConn = openURL(createStreamInfoURL("test_stream1"), HttpMethod.GET);

    Assert.assertEquals(HttpResponseStatus.NOT_FOUND.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();//ww  w  .  j  a  va  2s .c  o m

    // try to POST info to the non-existent stream
    urlConn = openURL(createURL("streams/non_existent_stream"), HttpMethod.POST);
    Assert.assertEquals(HttpResponseStatus.NOT_FOUND.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();

    // Now, create the new stream.
    urlConn = openURL(createURL("streams/test_stream1"), HttpMethod.PUT);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();

    // getInfo should now return 200
    urlConn = openURL(createStreamInfoURL("test_stream1"), HttpMethod.GET);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();
}

From source file:to.noc.devicefp.server.service.MaxMindServiceImpl.java

private MaxMindLocation createFromWebService(String ip) {
    MaxMindLocation location = null;//from  www .  ja  v  a2  s . c o m
    try {
        URL url = new URL("http://geoip.maxmind.com/e?l=" + maxMindLicenseKey + "&i=" + ip);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(10 * 1000); // 10 seconds

        BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream(), "ISO-8859-1"));

        String resultsLine = r.readLine();
        connection.disconnect();

        if (resultsLine != null) {
            // Split on a comma only if it has zero or an even number of quotes
            // after it. Assumes quotes are never escaped.
            String values[] = resultsLine.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");

            location = new MaxMindLocation();
            location.setIpAddress(ip);
            location.setStamp(new Date());

            for (GeoIpField field : GeoIpField.values()) {
                if (field.ordinal() >= values.length) {
                    break;
                }
                String val = values[field.ordinal()];
                // replace leading and trailing whitespace and quotes
                val = val.replaceAll("^\"?\\s*|\\s*\"?$", "");
                if (!val.isEmpty()) {
                    addLocationField(location, field, val);
                }
            }
        }
    } catch (Exception ex) {
        log.error("", ex);
        location = null;
    }
    return location;
}

From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java

private void disconnect(HttpURLConnection connection) {
    if (connection != null) {
        connection.disconnect();
    }
}

From source file:co.cask.cdap.gateway.handlers.StreamHandlerTest.java

@Test
public void testSimpleStreamEnqueue() throws Exception {
    // Create new stream.
    HttpURLConnection urlConn = openURL(createURL("streams/test_stream_enqueue"), HttpMethod.PUT);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();//from   ww w .j  a  va  2s .  co m

    // Enqueue 10 entries
    for (int i = 0; i < 10; ++i) {
        urlConn = openURL(createURL("streams/test_stream_enqueue"), HttpMethod.POST);
        urlConn.setDoOutput(true);
        urlConn.addRequestProperty("test_stream_enqueue.header1", Integer.toString(i));
        urlConn.getOutputStream().write(Integer.toString(i).getBytes(Charsets.UTF_8));
        Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
        urlConn.disconnect();
    }

    // Fetch 10 entries
    urlConn = openURL(createURL("streams/test_stream_enqueue/events?limit=10"), HttpMethod.GET);
    List<StreamEvent> events = GSON.fromJson(
            new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8),
            new TypeToken<List<StreamEvent>>() {
            }.getType());
    for (int i = 0; i < 10; i++) {
        StreamEvent event = events.get(i);
        int actual = Integer.parseInt(Charsets.UTF_8.decode(event.getBody()).toString());
        Assert.assertEquals(i, actual);
        Assert.assertEquals(Integer.toString(i), event.getHeaders().get("header1"));
    }
    urlConn.disconnect();
}

From source file:edu.isi.wings.util.oodt.CurationServiceAPI.java

private String query(String method, String op, Object... args) {
    String url = this.curatorurl + this.service + op;
    try {/*  www  .  ja  va2 s  . c  o  m*/
        String params = "policy=" + URLEncoder.encode(this.policy, "UTF-8");
        for (int i = 0; i < args.length; i += 2) {
            params += "&" + args[i] + "=" + URLEncoder.encode(args[i + 1].toString(), "UTF-8");
        }

        URL urlobj = new URL(url);
        if ("GET".equals(method))
            urlobj = new URL(url + "?" + params);
        HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
        con.setRequestMethod(method);
        if (!"GET".equals(method)) {
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();
        }

        String result = IOUtils.toString(con.getInputStream());
        con.disconnect();
        return result;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.oneops.metrics.es.ElasticsearchReporter.java

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
    if (connection.getResponseCode() != 200) {
        LOGGER.error("Reporting returned code {} {}: {}", connection.getResponseCode(),
                connection.getResponseMessage());
    }//w  w w  .  java2  s . c  o m
}

From source file:info.icefilms.icestream.browse.Location.java

private static Bitmap DownloadImage(URL url, Callback callback) {
    try {//from ww  w . j  a  v a  2  s  .c  o m
        // Open the connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0");
        urlConnection.setConnectTimeout(callback.GetConnectionTimeout());
        urlConnection.setReadTimeout(callback.GetConnectionTimeout());
        urlConnection.connect();

        // Get the input stream
        InputStream inputStream = urlConnection.getInputStream();

        // For some reason we can actually get a null InputStream instead of an exception
        if (inputStream == null) {
            Log.e("Ice Stream", "Image download failed. Unable to create Input Stream.");
            if (callback.GetErrorBoolean() == false) {
                callback.SetErrorBoolean(true);
                callback.SetErrorStringID(R.string.browse_image_download_error);
            }
            urlConnection.disconnect();
            return null;
        }

        // Download the image and create the bitmap
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

        // Close the connection
        inputStream.close();
        urlConnection.disconnect();

        // Check for errors
        if (bitmap == null) {
            Log.e("Ice Stream", "Image data decoding failed.");
            if (callback.GetErrorBoolean() == false) {
                callback.SetErrorBoolean(true);
                callback.SetErrorStringID(R.string.browse_image_decode_error);
            }
            return null;
        }

        return bitmap;
    } catch (SocketTimeoutException exception) {
        Log.e("Ice Stream", "Image download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_image_timeout_error);
        }
        return null;
    } catch (IOException exception) {
        Log.e("Ice Stream", "Image download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_image_download_error);
        }
        return null;
    }
}

From source file:ms.sujinkim.com.test.api.FoscamSnapshotRunnable.java

public void run() {
    ToastManager manager = ToastManager.getInstance();
    HttpURLConnection conn = null;
    String urlString = FoscamUrlFactory.getSnapshotUrl(camera);
    //DefaultHttpClient client = new DefaultHttpClient();
    try {/*from   w  w  w  .  j  av  a2 s  .c o m*/
        URL url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        int status = conn.getResponseCode();
        if (status != 200) {
            manager.makeToast("Unable to take snapshot: " + status);
            conn.disconnect();
            return;
        }

        String name = conn.getHeaderField(CONTENT_DISPOSITION);// ? name?  ?.
        InputStream inputStream = conn.getInputStream();
        if (inputStream != null) {
            writeSnapshot(name, inputStream);
            manager.makeToast("Saved \"" + name + "\"");
        }
    } catch (Exception e) {
        ToastManager.getInstance().makeToast("Unable to take snapshot: " + e.getMessage());
    } finally {
        conn.disconnect();
    }
}

From source file:org.hawkular.apm.client.api.rest.AbstractRESTClient.java

public <T> T withContext(String tenantId, URL url, Function<HttpURLConnection, T> function) {
    HttpURLConnection connection = null;
    try {//from   ww  w  .  j  av a 2s .c  o  m
        connection = getConnectionForGetRequest(tenantId, url);
        return function.apply(connection);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}