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:com.cloud.utils.UriUtils.java

public static Long getRemoteSize(String url) {
    Long remoteSize = (long) 0;
    HttpURLConnection httpConn = null;
    HttpsURLConnection httpsConn = null;
    try {//from ww w  .  j  ava  2 s. co m
        URI uri = new URI(url);
        if (uri.getScheme().equalsIgnoreCase("http")) {
            httpConn = (HttpURLConnection) uri.toURL().openConnection();
            if (httpConn != null) {
                httpConn.setConnectTimeout(2000);
                httpConn.setReadTimeout(5000);
                String contentLength = httpConn.getHeaderField("content-length");
                if (contentLength != null) {
                    remoteSize = Long.parseLong(contentLength);
                }
                httpConn.disconnect();
            }
        } else if (uri.getScheme().equalsIgnoreCase("https")) {
            httpsConn = (HttpsURLConnection) uri.toURL().openConnection();
            if (httpsConn != null) {
                String contentLength = httpsConn.getHeaderField("content-length");
                if (contentLength != null) {
                    remoteSize = Long.parseLong(contentLength);
                }
                httpsConn.disconnect();
            }
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URL " + url);
    } catch (IOException e) {
        throw new IllegalArgumentException("Unable to establish connection with URL " + url);
    }
    return remoteSize;
}

From source file:Main.java

static byte[] httpRequest(String url, byte[] requestBytes, int connectionTimeOutMs, int readTimeOutMs) {
    byte[] bArr = null;
    if (!(url == null || requestBytes == null)) {
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        try {/* ww  w .  jav  a 2 s.  co m*/
            urlConnection = (HttpURLConnection) new URL(url).openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(connectionTimeOutMs);
            urlConnection.setReadTimeout(readTimeOutMs);
            urlConnection.setFixedLengthStreamingMode(requestBytes.length);
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(requestBytes);
            outputStream.close();
            if (urlConnection.getResponseCode() != 200) {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            } else {
                inputStream = urlConnection.getInputStream();
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[16384];
                while (true) {
                    int chunkSize = inputStream.read(buffer);
                    if (chunkSize < 0) {
                        break;
                    } else if (chunkSize > 0) {
                        result.write(buffer, 0, chunkSize);
                    }
                }
                bArr = result.toByteArray();
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e2) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
        } catch (IOException e3) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e4) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e5) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
    return bArr;
}

From source file:Main.java

public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws IOException {
    HttpURLConnection urlConnection = null;
    try {/*  w ww .j a  v a  2 s .c o m*/
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:controllers.IndexServlet.java

private static void Convert(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) {
    response.setContentType("text/plain");

    try {/*  www.j a v a 2  s  .c om*/
        String fileName = request.getParameter("filename");
        String fileUri = DocumentManager.GetFileUri(fileName);
        String fileExt = FileUtility.GetFileExtension(fileName);
        FileType fileType = FileUtility.GetFileType(fileName);
        String internalFileExt = DocumentManager.GetInternalExtension(fileType);

        if (DocumentManager.GetConvertExts().contains(fileExt)) {
            String key = ServiceConverter.GenerateRevisionId(fileUri);

            Pair<Integer, String> res = ServiceConverter.GetConvertedUri(fileUri, fileExt, internalFileExt, key,
                    true);

            int result = res.getKey();
            String newFileUri = res.getValue();

            if (result != 100) {
                writer.write("{ \"step\" : \"" + result + "\", \"filename\" : \"" + fileName + "\"}");
                return;
            }

            String correctName = DocumentManager
                    .GetCorrectName(FileUtility.GetFileNameWithoutExtension(fileName) + internalFileExt);

            URL url = new URL(newFileUri);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            InputStream stream = connection.getInputStream();

            if (stream == null) {
                throw new Exception("Stream is null");
            }

            File convertedFile = new File(DocumentManager.StoragePath(correctName, null));
            try (FileOutputStream out = new FileOutputStream(convertedFile)) {
                int read;
                final byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }

                out.flush();
            }

            connection.disconnect();

            //remove source file ?
            //File sourceFile = new File(DocumentManager.StoragePath(fileName, null));
            //sourceFile.delete();

            fileName = correctName;
        }

        writer.write("{ \"filename\" : \"" + fileName + "\"}");

    } catch (Exception ex) {
        writer.write("{ \"error\": \"" + ex.getMessage() + "\"}");
    }
}

From source file:edu.stanford.epadd.launcher.Splash.java

private static boolean killRunningServer(String url) throws IOException {
    try {//from w  w w. j  a  v  a 2  s  . co  m
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false
        String http = url
                + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20ePADD"; // version num spaces and brackets screw up the URL connection
        out.println("Sending a kill request to " + http);
        HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection();
        u.connect();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:com.meetingninja.csse.database.ContactDatabaseAdapter.java

public static List<Contact> getContacts(String userID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(userID).build().toString();
    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // add request header

    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);// ww w . j a  va 2  s  .  c o m
    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    List<Contact> contacts = new ArrayList<Contact>();
    List<String> contactIds = new ArrayList<String>();
    List<String> relationIds = new ArrayList<String>();
    final JsonNode contactsArray = MAPPER.readTree(response).get(Keys.User.CONTACTS);
    if (contactsArray.isArray()) {
        for (final JsonNode userNode : contactsArray) {
            relationIds.add(userNode.get(Keys.User.RELATIONID).asText());
            contactIds.add(userNode.get(Keys.User.CONTACTID).asText());
        }
    }

    conn.disconnect();
    for (int i = 0; i < contactIds.size(); i++) {

        User contact = UserDatabaseAdapter.getUserInfo(contactIds.get(i));
        if (contact != null) {
            Contact oneContact = new Contact(contact, relationIds.get(i));
            contacts.add(oneContact);
        }
    }
    return contacts;
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *///from w  w  w. j  a  v  a 2s .  co  m
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:no.ntnu.wifimanager.ServerUtilities.java

/**
 * Issue a POST request to server.//from w  ww.j a  va2s  .c  o  m
 *
 * @param serverUrl POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(serverUrl);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + serverUrl);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(LOG_TAG, "Posting '" + body + "' to " + url);
    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);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java

private static String getCookie(String authToken) throws IOException {
    HttpURLConnection connection = null;
    try {//from w w  w.  j a  v  a 2  s  .  co m
        connection = (HttpURLConnection) new URL(
                BuildConfig.HOST + "/_ah/login?continue=http://localhost/&auth=" + authToken).openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.connect();
        if (connection.getResponseCode() != 302) {
            Log.e(TAG, "Cannot fetch the cookie: " + connection.getResponseCode());
            return null;
        }
        String cookie = connection.getHeaderField("Set-Cookie");
        if (!cookie.contains("SACSID")) {
            return null;
        }
        return cookie;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.brobwind.brodm.NetworkUtils.java

public static void deviceInfo(String path, OnMessage callback) {
    try {//w w  w. j  a va 2s  .co  m
        URL url = new URL(path + "/privet/info");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic anonymous");
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.connect();
        try {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader bufReader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            for (String line = bufReader.readLine(); line != null;) {
                sb.append(line).append("\n");
                line = bufReader.readLine();
            }

            callback.onMessage(sb.toString(), null);
            return;
        } finally {
            urlConnection.disconnect();
        }
    } catch (MalformedURLException muex) {
        Log.e(TAG, "Malformed url: " + path);
        callback.onMessage(null, muex.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        callback.onMessage(null, e.getMessage());
    }
}