Example usage for java.net URLConnection getInputStream

List of usage examples for java.net URLConnection getInputStream

Introduction

In this page you can find the example usage for java.net URLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:no.ntnu.idi.socialhitchhiking.map.RouteProvider.java

/**
 * Creates a connection from the given URL, and returns an {@link InputStream} for reading data.
 * /*from  ww  w. j a v  a2  s  .  com*/
 * @param url The URL that the connection refer to.
 * @return Returns an {@link InputStream} for reading data.
 * @throws IOException 
 * @throws MalformedURLException 
 */
private static InputStream getConnectionInputStream(String url) throws MalformedURLException, IOException {
    URLConnection conn = new URL(url).openConnection();
    return conn.getInputStream();
}

From source file:fuliao.fuliaozhijia.data.UserData.java

public static String download(String mediaId, String dir) {
    //      http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
    URL source;//from w  w w.  j a v a2 s . c  om
    try {
        source = new URL("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
                + "oPaVk_NjH_TCX1fQhIVz_8DoRqE85Vx2E_sawJWQXpen5Q6HykjRnqA--6yE-y2VaQTU1f3vY5K-udylcgm55igkwa--7kVQ-KyDndcylmE"
                //WeixinAccessUtil.getAccessToken()
                + "&media_id=" + mediaId);
        URLConnection connection = source.openConnection();
        connection.setConnectTimeout(60 * 1000);
        connection.setReadTimeout(300 * 1000);
        InputStream input = connection.getInputStream();
        String fileType = connection.getHeaderField("Content-disposition");
        System.out.println("Content-disposition:" + fileType);
        String fileName = UUID.randomUUID().toString()
                + fileType.substring(fileType.lastIndexOf("."), fileType.length() - 1);
        File file = new File(dir + fileName);
        FileUtils.copyInputStreamToFile(input, file);
        return fileName;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.oracle.tutorial.jdbc.DatalinkSample.java

public static void viewTable(Connection con, Proxy proxy) throws SQLException, IOException {
    Statement stmt = null;/*ww  w. j a v  a  2  s  .c o  m*/
    String query = "SELECT document_name, url FROM data_repository";

    try {
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        if (rs.next()) {
            String documentName = null;
            java.net.URL url = null;

            documentName = rs.getString(1);

            // Retrieve the value as a URL object.
            url = rs.getURL(2);

            if (url != null) {

                // Retrieve the contents from the URL.
                URLConnection myURLConnection = url.openConnection(proxy);
                BufferedReader bReader = new BufferedReader(
                        new InputStreamReader(myURLConnection.getInputStream()));

                System.out.println("Document name: " + documentName);

                String pageContent = null;

                while ((pageContent = bReader.readLine()) != null) {
                    // Print the URL contents
                    System.out.println(pageContent);
                }
            } else {
                System.out.println("URL is null");
            }
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } catch (IOException ioEx) {
        System.out.println("IOException caught: " + ioEx.toString());
    } catch (Exception ex) {
        System.out.println("Unexpected exception");
        ex.printStackTrace();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:jmupen.JMupenUpdater.java

/**
 * Returns bytes for connection./*from   ww w  .j  a v  a2  s  .  com*/
 *
 * @param aConnection
 * @return bytes
 * @throws java.io.IOException
 */
public static byte[] getBytes(URLConnection aConnection) throws IOException {
    InputStream stream = aConnection.getInputStream(); // Get stream for connection
    byte bytes[] = getBytes(stream); // Get bytes for stream
    stream.close(); // Close stream
    return bytes; // Return bytes
}

From source file:com.BibleQuote.utils.FsUtils.java

public static boolean loadContentFromURL(String fromURL, String toFile) {
    try {//  w w w . jav a2s .  c  o m
        URL url = new URL("http://bible-desktop.com/xml" + fromURL);
        File file = new File(toFile);

        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();

        /* Define InputStreams to read from the URLConnection */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        /* Read bytes to the Buffer until there is nothing more to read(-1) */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();

    } catch (IOException e) {
        Log.e(TAG, String.format("loadContentFromURL(%1$s, %2$s)", fromURL, toFile), e);
        return false;
    }

    return true;
}

From source file:be.solidx.hot.utils.IOUtils.java

public static InputStream loadResourceNoCache(URL path) throws IOException {
    URLConnection resConn = path.openConnection();
    // !!! needed to avoid jvm resource catching
    resConn.setUseCaches(false);/*  www. j a  va  2s.c om*/
    return resConn.getInputStream();
}

From source file:be.solidx.hot.utils.IOUtils.java

public static InputStream loadResourceNoCache(String path) throws IOException {
    URL res = IOUtils.class.getClassLoader().getResource(path);

    if (res == null) {
        throw new IOException("Resource " + path + " does not exists");
    }/*w  w w.  j  a  va2  s . c  o m*/
    URLConnection resConn = res.openConnection();
    // !!! needed to avoid jvm resource catching
    resConn.setUseCaches(false);
    return resConn.getInputStream();
}

From source file:ch.ethz.inf.vs.android.g54.a4.net.RequestHandler.java

/**
 * Downloads image from given URL and converts it to a Bitmap
 * //  ww w  . ja v a 2 s  .  c o m
 * @throws ConnectionException
 * @throws UnrecognizedResponseException
 */
public static Bitmap getBitmap(String imageURL) throws ConnectionException, UnrecognizedResponseException {
    Log.d(TAG, "download image from:" + imageURL);

    try {
        URL url = new URL(imageURL);

        // Open a connection to URL
        URLConnection ucon = url.openConnection();

        // Define InputStreams to read from the URLConnection.
        InputStream is = ucon.getInputStream();

        // Read stream into a bitmap
        return BitmapFactory.decodeStream(is);
    } catch (MalformedURLException e) {
        String msg = String.format("Could not resolve url %s.", imageURL);
        throw new ConnectionException(msg, e);
    } catch (IOException e) {
        String msg = String.format("Could not download image from %s.", imageURL);
        throw new UnrecognizedResponseException(msg, e);
    }
}

From source file:ca.mudar.parkcatcher.utils.ParserUtils.java

public static JSONTokener newJsonTokenerParser(URL url) throws IOException {

    final URLConnection tc = url.openConnection();

    final BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
    String line;//from  ww w .  ja  va  2 s.  c o  m
    String str = "";
    try {
        while ((line = in.readLine()) != null) {
            str += line;
        }

    } catch (IOException e) {
        throw e;
    } finally {
        in.close();
    }

    try {
        final JSONTokener parser = new JSONTokener(str);
        return parser;
    } catch (NullPointerException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:cloudworker.RemoteWorker.java

private static void cleanUpInstance() {
    /*try {/*from ww w. ja  va  2 s  .  c  om*/
       CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds);
    ec2.cancelSpotInstanceRequests(cancelRequest);
    } catch (AmazonServiceException e) {
    // Write out any exceptions that may have occurred.
    System.out.println("Error cancelling instances");
    System.out.println("Caught Exception: " + e.getMessage());
    System.out.println("Reponse Status Code: " + e.getStatusCode());
    System.out.println("Error Code: " + e.getErrorCode());
    System.out.println("Request ID: " + e.getRequestId());
      }*/

    List<String> instanceId = new ArrayList<String>();
    String inputLine;
    URL EC2MetaData;

    try {
        EC2MetaData = new URL("http://169.254.169.254/latest/meta-data/instance-id");
        URLConnection EC2MD = EC2MetaData.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(EC2MD.getInputStream()));
        while ((inputLine = in.readLine()) != null) {
            instanceId.add(inputLine);
        }
        in.close();
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Terminate instances.
        TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceId);
        ec2.terminateInstances(terminateRequest);
    } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.out.println("Error terminating instances");
        System.out.println("Caught Exception: " + e.getMessage());
        System.out.println("Reponse Status Code: " + e.getStatusCode());
        System.out.println("Error Code: " + e.getErrorCode());
        System.out.println("Request ID: " + e.getRequestId());
    }

}