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:mdretrieval.FileFetcher.java

public static String[] loadStringFromURL(String destinationURL, boolean acceptRDF) throws IOException {
    String[] ret = new String[2];

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;

    String dest = destinationURL;
    URL url = new URL(dest);
    Proxy proxy = null;/*w  w  w .j  a  v a  2  s.c  o  m*/

    if (ServerConstants.isProxyEnabled) {
        proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(ServerConstants.hostname, ServerConstants.port));
        urlConnection = (HttpURLConnection) url.openConnection(proxy);
    } else {
        urlConnection = (HttpURLConnection) url.openConnection();
    }

    boolean redirect = false;

    int status = urlConnection.getResponseCode();
    if (Master.DEBUG_LEVEL >= Master.LOW)
        System.out.println("RESPONSE-CODE--> " + status);
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            redirect = true;
    }

    if (redirect) {
        String newUrl = urlConnection.getHeaderField("Location");
        dest = newUrl;
        urlConnection.disconnect();
        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println("REDIRECT--> " + newUrl);
        urlConnection = openMaybeProxyConnection(proxy, newUrl);
    }

    try {
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        urlConnection.setDoInput(true);
        //urlConnection.setDoOutput(true);            
        inputStream = urlConnection.getInputStream();
        ret[1] = urlConnection.getHeaderField("Content-Type");
    } catch (IllegalStateException e) {
        if (Master.DEBUG_LEVEL >= Master.LOW)
            System.out.println(" DEBUG: IllegalStateException");
        urlConnection.disconnect();
        HttpURLConnection conn2 = openMaybeProxyConnection(proxy, dest);
        conn2.setRequestMethod("GET");
        conn2.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        conn2.setDoInput(true);
        inputStream = conn2.getInputStream();
        ret[1] = conn2.getHeaderField("Content-Type");
    }

    try {
        ret[0] = IOUtils.toString(inputStream);

        if (Master.DEBUG_LEVEL > Master.LOW) {
            System.out.println(" Content-type: " + urlConnection.getHeaderField("Content-Type"));
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
        urlConnection.disconnect();
    }

    if (Master.DEBUG_LEVEL > Master.LOW)
        System.out.println("Done reading " + destinationURL);
    return ret;

}

From source file:Main.java

public static String callJsonAPI(String urlString) {
    // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient
    HttpURLConnection urlConnection = null;
    StringBuilder jsonResult = new StringBuilder();

    try {//  ww w  .jav a2  s . c o m
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(TIMEOUT_CONNECTION);
        urlConnection.setReadTimeout(TIMEOUT_READ);
        urlConnection.connect();

        int status = urlConnection.getResponseCode();

        switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                jsonResult.append(line).append("\n");
            }
            br.close();
        }
    } catch (MalformedURLException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } catch (IOException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } finally {
        if (urlConnection != null) {
            try {
                urlConnection.disconnect();
            } catch (Exception e) {
                System.err.print(e.getMessage());
            }
        }
    }
    return jsonResult.toString();
}

From source file:Main.java

/**
 * Issue a POST request to the server./*from   w w  w.  ja  va 2 s. c  o  m*/
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws IOException
 *             propagated from POST.
 */
public static String post_t(String endpoint, Map<String, Object> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, Object> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", contentType);
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.max2idea.android.fwknop.Fwknop.java

public static String getExternalIP() {
    URL Url = null;/*from  ww  w.  j av  a 2  s  .  c  o  m*/
    HttpURLConnection Conn = null;
    InputStream InStream = null;
    InputStreamReader Isr = null;
    String extIP = "";

    try {
        Url = new java.net.URL("http://ifconfig.me/ip");
        Conn = (HttpURLConnection) Url.openConnection();
        InStream = Conn.getInputStream();
        Isr = new java.io.InputStreamReader(InStream);
        BufferedReader Br = new java.io.BufferedReader(Isr);
        extIP = Br.readLine();
        Log.v("External IP", "Your external IP address is " + extIP);
    } catch (Exception ex) {
        Logger.getLogger(Fwknop.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        //            Isr.close();
        //            InStream.close();
        Conn.disconnect();
    }
    return extIP;

}

From source file:com.googlesource.gerrit.plugins.its.jira.restapi.JiraRestApi.java

private boolean sendPayload(String method, String spec, String jsonInput, int passCode) throws IOException {
    HttpURLConnection conn = prepHttpConnection(spec, method, true);
    try {/*from  w  w  w  .  j av a2s  .c  o  m*/
        writeBodyData(jsonInput, conn);
        return validateResponse(conn, passCode, null);
    } finally {
        conn.disconnect();
    }
}

From source file:com.juick.android.Utils.java

public static int doHttpGetRequest(String url) {
    try {//from   www  . ja  v a2s .  com
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setUseCaches(false);
        conn.connect();
        int status = conn.getResponseCode();
        conn.disconnect();
        return status;
    } catch (Exception e) {
        Log.e("doHttpGetRequest", e.toString());
    }
    return 0;
}

From source file:com.example.scandevice.MainActivity.java

public static String excutePost(String targetURL, String urlParameters) {
    URL url;// ww  w.  ja  v a2 s. c o m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

    } catch (Exception e) {
        e.printStackTrace();
        return "Don't post data";

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return "Data Sent";
}

From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java

/**
 * Issue a POST request to the server./*from  w ww. java2s  .c  o m*/
 * 
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 * 
 * @throws IOException
 *             propagated from POST.
 */
public static boolean post(String endpoint, Map<String, String> params) {
    URL url = null;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        //Fail silently
    }

    byte[] bytes = constructParams(params);

    HttpURLConnection conn;

    long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
    for (int i = 1; i <= HttpUtilities.MAX_ATTEMPTS; i++) {
        try {
            conn = makePostConnection(url, bytes);

            // handle the response
            int status = conn.getResponseCode();

            if (status == 200) {
                //Useful for debugging
                /*
                BufferedReader br = 
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                  sb.append(line+"\n");
                    }
                    br.close();
                    Log.d("output", sb.toString());
                 */

                if (null != conn) {
                    conn.disconnect();
                }
                return true;
            }

            else if (500 > status) {
                if (null != conn) {
                    conn.disconnect();
                }
                return false;
            }
        } catch (IOException e) {
            try {
                Thread.sleep(backoff);
            } catch (InterruptedException e1) {
                // Activity finished before we complete - exit.
                Thread.currentThread().interrupt();
            }
            // increase backoff exponentially
            backoff *= 2;
        }
    }

    return false;
}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test method for.//from  w  w w  .  j  a  v a 2s . com
 *
 * @throws Exception the exception
 * {@link ext.services.network.NetworkUtils#getConnection(java.lang.String, ext.services.network.Proxy)}
 * .
 */
public void testGetConnectionStringProxy() throws Exception {
    // null when no connection is allowed
    Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "true");
    assertNull(NetworkUtils.getConnection(URL, null));
    // useful content when inet access is allowed
    Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false");
    HttpURLConnection connection = NetworkUtils.getConnection(URL, null);
    assertNotNull(connection);
    connection.disconnect();
}

From source file:org.apache.nifi.minifi.integration.util.LogUtil.java

public static void verifyLogEntries(String expectedJsonFilename, Container container) throws Exception {
    List<ExpectedLogEntry> expectedLogEntries;
    try (InputStream inputStream = LogUtil.class.getClassLoader().getResourceAsStream(expectedJsonFilename)) {
        List<Map<String, Object>> expected = new ObjectMapper().readValue(inputStream, List.class);
        expectedLogEntries = expected.stream()
                .map(map -> new ExpectedLogEntry(Pattern.compile((String) map.get("pattern")),
                        (int) map.getOrDefault("occurrences", 1)))
                .collect(Collectors.toList());
    }//from   ww  w .j  a  v a  2s  . c  om
    DockerPort dockerPort = container.port(8000);
    URL url = new URL("http://" + dockerPort.getIp() + ":" + dockerPort.getExternalPort());
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try (InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
        String line;
        for (ExpectedLogEntry expectedLogEntry : expectedLogEntries) {
            boolean satisfied = false;
            int occurrences = 0;
            while ((line = bufferedReader.readLine()) != null) {
                if (expectedLogEntry.pattern.matcher(line).find()) {
                    logger.info("Found expected: " + line);
                    if (++occurrences >= expectedLogEntry.numOccurrences) {
                        logger.info("Found target " + occurrences + " times");
                        satisfied = true;
                        break;
                    }
                }
            }
            if (!satisfied) {
                fail("End of log reached without " + expectedLogEntry.numOccurrences + " match(es) of "
                        + expectedLogEntry.pattern);
            }
        }
    } finally {
        urlConnection.disconnect();
    }
}