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.lurencun.cfuture09.androidkit.http.Http.java

/**
 * /* w w  w  .  ja va  2s  .c  o  m*/
 *
 * @param url
 *            ?
 * @param savePath
 *            ??
 * @param overwrite
 *            ?
 * @throws IOException
 *             ??io
 */
public static void download(String url, File savePath, boolean overwrite) throws IOException {
    if (savePath == null) {
        throw new IOException("the second parameter couldn't be null");
    }
    if (savePath.exists() && (!overwrite || savePath.isDirectory())) {
        throw new IOException("the file specified is exist or cannot be overwrite");
    }
    savePath.getParentFile().mkdirs();

    HttpURLConnection connection = null;
    InputStream input = null;
    FileOutputStream output = null;
    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        input = connection.getInputStream();
        output = new FileOutputStream(savePath);
        byte[] buffer = new byte[BUFFER_SIZE];
        int readSize = 0;
        while ((readSize = input.read(buffer)) != -1) {
            output.write(buffer, 0, readSize);
        }
        output.flush();
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.exoplatform.utils.image.CookieAwarePicassoDownloader.java

@Override
public Response load(Uri uri, int networkPolicy) throws IOException {
    // TODO use networkPolicy as in com.squareup.picasso.UrlConnectionDownloader
    // https://github.com/square/picasso/blob/picasso-parent-2.5.2/picasso/src/main/java/com/squareup/picasso/UrlConnectionDownloader.java
    HttpURLConnection connection = connection(uri);
    connection.setUseCaches(true);//w  w w  .jav a 2  s.  c  om

    int responseCode = connection.getResponseCode();
    if (responseCode >= 300) {
        connection.disconnect();
        throw new ResponseException(responseCode + " " + connection.getResponseMessage(), networkPolicy,
                responseCode);
    }

    long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
    // boolean fromCache =
    // parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE));
    boolean fromCache = false;

    return new Response(connection.getInputStream(), fromCache, contentLength);
}

From source file:filters.BaseFilter.java

public void filter(URL url, OutputStream output, FilterOptions options)
        throws IOException, EmptyExtensionException, NotSupportedFormatException, FileTooBigException {
    String format = SupportedFormats.supportFormat(url.toString());
    if (StringUtils.isBlank(format)) {
        throw new NotSupportedFormatException();
    }//from   ww  w.java  2 s . com

    // Calculate size
    HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
    int contentLength = openConnection.getContentLength();
    if (contentLength > FILE_SIZE_LIMIT) {
        throw new FileTooBigException();
    }
    openConnection.disconnect();

    BufferedImage read = ImageIO.read(url);
    doFilter(read, output, options, format);
}

From source file:org.wso2.msf4j.client.test.ClientTest.java

@Test
public void testClient() throws Exception {
    HttpURLConnection urlConn = request("/report/invoice/I001", HttpMethod.GET, false);
    InputStream inputStream = urlConn.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);//  ww w . j  a v  a  2s .co m
    urlConn.disconnect();
    Assert.assertEquals(response,
            "{\"id\":\"I001\",\"customer\":{\"id\":\"C001\",\"firstName\":\"WSO2\",\"lastName\":"
                    + "\"Inc\",\"address\":\"Colombo\"},\"amount\":250.15}");

    urlConn = request("/report/invoice/I002", HttpMethod.GET, false);
    int responseCode = urlConn.getResponseCode();
    Assert.assertEquals(responseCode, 404);
    inputStream = urlConn.getErrorStream();
    response = StreamUtil.asString(inputStream);
    Gson gson = new Gson();
    InvoiceNotFoundResponseMapper invoiceNotFoundResponseMapper = gson.fromJson(response,
            InvoiceNotFoundResponseMapper.class);
    IOUtils.closeQuietly(inputStream);
    Assert.assertEquals(invoiceNotFoundResponseMapper.getExceptionKey(), "30002");
    Assert.assertEquals(invoiceNotFoundResponseMapper.getExceptionClass(),
            InvoiceNotFoundRestServiceException.class);
    urlConn.disconnect();
}

From source file:core.RESTCalls.RESTPost.java

public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

    conn.setDoOutput(true);/*ww w  .  j  a  v  a 2 s .  co m*/
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    OutputStream out = conn.getOutputStream();

    Writer writer = new OutputStreamWriter(out, "UTF-8");

    for (int i = 0; i < paramName.length; i++) {

        writer.write(paramName[i]);
        writer.write("=");
        writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
        writer.write("&");
    }

    writer.close();
    out.close();

    if (conn.getResponseCode() != 200)
        throw new IOException(conn.getResponseMessage());

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    StringBuilder sb = new StringBuilder();

    String line;

    while ((line = rd.readLine()) != null)
        sb.append(line + "\n");

    rd.close();

    conn.disconnect();

    return sb.toString();
}

From source file:com.gliffy.restunit.http.JavaHttp.java

/** Performs an HTTP GET.
 * @param request the request describing the GET.
 * @return a response/*from  w ww.jav a 2s  .  c om*/
 * @throws IOException if HttpURLConnection generated an IO Exception
 */
public HttpResponse get(HttpRequest request) throws IOException {
    HttpURLConnection connection = getConnection(request);
    connection.setRequestMethod("GET");
    connection.connect();
    HttpResponse response = createResponse(connection);
    connection.disconnect();
    return response;
}

From source file:Main.java

public static String getPosthtml(String posturl, String postData, String encode) {

    String html = "";
    URL url;/* ww  w.j ava2s  . c o m*/
    try {
        url = new URL(posturl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("User-Agent", userAgent);

        String postDataStr = postData;
        byte[] bytes = postDataStr.getBytes("utf-8");
        connection.setRequestProperty("Content-Length", "" + bytes.length);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setDoOutput(true);
        connection.setReadTimeout(timeout);
        connection.setFollowRedirects(true);
        connection.connect();
        OutputStream outStrm = connection.getOutputStream();
        outStrm.write(bytes);
        outStrm.flush();
        outStrm.close();
        InputStream inStrm = connection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, encode));

        String temp = "";
        while ((temp = br.readLine()) != null) {
            html += (temp + '\n');
        }
        br.close();
        connection.disconnect();

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

}

From source file:com.gliffy.restunit.http.JavaHttp.java

/** Performs an HTTP HEAD. 
 * @param request the request describing the HEAD.
 * @return a response/*from   w  ww. ja v a 2  s  .  co m*/
 * @throws IOException if HttpURLConnection generated an IO Exception
 */
public HttpResponse head(HttpRequest request) throws IOException {
    HttpURLConnection connection = getConnection(request);
    connection.setRequestMethod("HEAD");
    connection.connect();
    HttpResponse response = createResponse(connection);
    connection.disconnect();
    return response;
}

From source file:com.moviejukebox.plugin.OpenSubtitlesPlugin.java

private static boolean subtitleDownload(Movie movie, File movieFile, File subtitleFile) {
    try {/*  w w  w . ja  v a 2  s  .c o  m*/
        String ret;
        String xml;

        String moviehash = getHash(movieFile);
        String moviebytesize = String.valueOf(movieFile.length());

        xml = generateXMLRPCSS(moviehash, moviebytesize);
        ret = sendRPC(xml);

        String subDownloadLink = getValue("SubDownloadLink", ret);

        if (StringUtils.isBlank(subDownloadLink)) {
            String moviefilename = movieFile.getName();

            // Do not search by file name for BD rip files in the format 0xxxx.m2ts
            if (!(moviefilename.toUpperCase().endsWith(".M2TS") && moviefilename.startsWith("0"))) {

                // Try to find the subtitle using file name
                String subfilename = subtitleFile.getName();
                int index = subfilename.lastIndexOf('.');

                String query = subfilename.substring(0, index);

                xml = generateXMLRPCSS(query);
                ret = sendRPC(xml);

                subDownloadLink = getValue("SubDownloadLink", ret);
            }
        }

        if (StringUtils.isBlank(subDownloadLink)) {
            LOG.debug("Subtitle not found for {}", movieFile.getName());
            return Boolean.FALSE;
        }

        LOG.debug("Download subtitle for {}", movie.getBaseName());

        URL url = new URL(subDownloadLink);
        HttpURLConnection connection = (HttpURLConnection) (url
                .openConnection(YamjHttpClientBuilder.getProxy()));
        connection.setRequestProperty("Connection", "Close");

        try (InputStream inputStream = connection.getInputStream()) {
            int code = connection.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                LOG.error("Download Failed");
                return Boolean.FALSE;
            }
            FileTools.copy(inputStream, new FileOutputStream(subtitleFile));

        } finally {
            connection.disconnect();
        }

        String subLanguageID = getValue("SubLanguageID", ret);
        if (StringUtils.isNotBlank(subLanguageID)) {
            SubtitleTools.addMovieSubtitle(movie, subLanguageID);
        } else {
            SubtitleTools.addMovieSubtitle(movie, "YES");
        }

        return Boolean.TRUE;

    } catch (Exception ex) {
        LOG.error("Download Exception (Movie Not Found)", ex);
        return Boolean.FALSE;
    }

}

From source file:com.gliffy.restunit.http.JavaHttp.java

/** Performs an HTTP DELETE. 
 * @param request the request describing the DELETE.
 * @return a response/*from   ww w.j a  v a 2 s .c o m*/
 * @throws IOException if HttpURLConnection generated an IO Exception
 */
public HttpResponse delete(HttpRequest request) throws IOException {
    HttpURLConnection connection = getConnection(request);
    connection.setRequestMethod("DELETE");
    connection.connect();
    HttpResponse response = createResponse(connection);
    connection.disconnect();
    return response;
}