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.google.api.ads.adwords.awreporting.server.appengine.exporter.ReportExporterAppEngine.java

public static void html2PdfOverNet(InputStream htmlSource, ReportWriter reportWriter) {
    try {/*  w  ww .j  av a  2s. c om*/
        URL url = new URL(HTML_2_PDF_SERVER_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/html");
        connection.setRequestProperty("charset", "utf-8");
        connection.setUseCaches(false);

        DataOutputStream send = new DataOutputStream(connection.getOutputStream());
        send.write(IOUtils.toByteArray(htmlSource));
        send.flush();

        // Read from connection
        reportWriter.write(connection.getInputStream());

        send.close();

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.gson.util.HttpKit.java

/**
 * /*from   w w w  .j av a  2s  .com*/
 * @description 
 * ??: get 
 * @return       : 
 * @throws IOException 
 * @throws UnsupportedEncodingException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static String get(String url, Map<String, String> params, Map<String, String> headers)
        throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException,
        UnsupportedEncodingException, IOException {
    HttpURLConnection http = null;
    if (isHttps(url)) {
        http = initHttps(initParams(url, params), _GET, headers);
    } else {
        http = initHttp(initParams(url, params), _GET, headers);
    }
    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    StringBuffer bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
        http.disconnect();// 
    }
    return bufferRes.toString();
}

From source file:Main.java

public static String getHtml(String getUrl, int outtime, String charsetName) {
    String html = "";
    URL url;/*  www .  j av a 2 s .c  o  m*/
    try {
        url = new URL(getUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1; CIBA)");
        // connection.setRequestProperty("Connection", "Keep-Alive");
        // connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setConnectTimeout(outtime);
        connection.connect();
        InputStream inStrm = connection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, charsetName));
        String temp = "";

        while ((temp = br.readLine()) != null) {
            html = html + (temp + '\n');
        }
        try {
            br.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
        try {
            connection.disconnect();
        } catch (Exception e) {
            // TODO: handle exception
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return html;
}

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

public static Schedule getSchedule(String userID) throws JsonParseException, JsonMappingException, IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Schedule").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);//w  w  w .  j a va  2  s . c om

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    Schedule sched = parseSchedule(MAPPER.readTree(response));

    conn.disconnect();
    return sched;
}

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

private static boolean isURLAlive(String url) throws IOException {
    try {/*from   w w w.ja v  a 2s  .  c om*/
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false

        // since "index" may auto load default archive, attach it to session, and redirect to "info" page,
        // we need to maintain the session across the pages.
        // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

        out.println("Testing liveness at " + url);
        HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:connector.ISConnector.java

public static JSONObject processRequest(String servlet, byte[] query) {
    JSONObject response = null;//from www .  j  a va2s. c  o  m
    if (servlet != null && !servlet.startsWith("/"))
        servlet = "/" + servlet;
    try {
        // Establish HTTP connection with Identity Service
        URL url = new URL(CONTEXT_PATH + servlet);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        //Create the form content
        try (OutputStream out = conn.getOutputStream()) {
            out.write(query);
            out.close();
        }

        // Buffer the result into a string
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }

        rd.close();
        conn.disconnect();
        response = (JSONObject) new JSONParser().parse(sb.toString());

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

    return response;
}

From source file:Main.java

static void getHTTPXml(URL url) throws Exception {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("ACCEPT", "application/xml");
    InputStream xml = conn.getInputStream();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document document = builder.parse(xml);

    System.out.println(document);
    String doctype = conn.getContentType();
    System.out.println(doctype);//from ww w .  ja v  a2  s . c  om

    XPathFactory pathFactory = XPathFactory.newInstance();
    XPath path = pathFactory.newXPath();
    XPathExpression expression;
    expression = path.compile("/result/checkid");
    NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
    String checkids[] = getNodeValue(nodeList);
    for (String checkid : checkids) {
        System.out.print(checkid + ", ");
    }
    conn.disconnect();
}

From source file:com.iStudy.Study.Renren.Util.java

public static String uploadFile(String reqUrl, Bundle parameters, String fileParamName, String filename,
        String contentType, byte[] data) {
    HttpURLConnection urlConn = null;
    try {/*from w  w w.  j  a  v  a  2s.c o  m*/
        urlConn = sendFormdata(reqUrl, parameters, fileParamName, filename, contentType, data);
        String responseContent = read(urlConn.getInputStream());
        return responseContent.trim();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
}

From source file:Main.java

public static boolean downloadFile(File file, URL url) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    HttpURLConnection conn = null;
    try {/*from   w  w  w . j a  v  a2  s  .  c  o  m*/
        conn = (HttpURLConnection) url.openConnection();
        bis = new BufferedInputStream(conn.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream(file));

        int contentLength = conn.getContentLength();

        byte[] buffer = new byte[BUFFER_SIZE];
        int read = 0;
        int count = 0;
        while ((read = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
            count += read;
        }
        if (count < contentLength)
            return false;
        int responseCode = conn.getResponseCode();
        if (responseCode / 100 != 2) {
            // error
            return false;
        }
        // finished
        return true;
    } finally {
        try {
            bis.close();
            bos.close();
            conn.disconnect();
        } catch (Exception e) {
        }
    }
}

From source file:com.manning.androidhacks.hack040.util.ImageFetcher.java

/**
 * Download a bitmap from a URL, write it to a disk and return the File
 * pointer. This implementation uses a simple disk cache.
 * //from w  ww .  j  a  v  a2  s.co  m
 * @param context
 *          The context to use
 * @param urlString
 *          The URL to fetch
 * @param cache
 *          The disk cache instance to get the download directory from.
 * @return A File pointing to the fetched bitmap
 */
public static File downloadBitmap(Context context, String urlString, DiskLruCache cache) {
    final File cacheFile = new File(cache.createFilePath(urlString));

    if (cache.containsKey(urlString)) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "downloadBitmap - found in http cache - " + urlString);
        }
        return cacheFile;
    }

    if (BuildConfig.DEBUG) {
        Log.d(TAG, "downloadBitmap - downloading - " + urlString);
    }

    Utils.disableConnectionReuseIfNecessary();
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;

    try {
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        final InputStream in = new BufferedInputStream(urlConnection.getInputStream(), Utils.IO_BUFFER_SIZE);
        out = new BufferedOutputStream(new FileOutputStream(cacheFile), Utils.IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        cache.putFromFetcher(urlString);
        return cacheFile;

    } catch (final IOException e) {
        Log.e(TAG, "Error in downloadBitmap - " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                Log.e(TAG, "Error in downloadBitmap - " + e);
            }
        }
    }

    return null;
}