Example usage for java.net HttpURLConnection getInputStream

List of usage examples for java.net HttpURLConnection getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.moviejukebox.plugin.trailer.AppleTrailersPlugin.java

private static String getTrailerRealUrl(String trailerUrl) {
    try {//from www  .j  av  a2 s.  co m
        URL url = new URL(trailerUrl);
        HttpURLConnection connection = (HttpURLConnection) (url
                .openConnection(YamjHttpClientBuilder.getProxy()));
        try (InputStream inputStream = connection.getInputStream()) {
            byte[] buf = new byte[1024];
            int len;
            len = inputStream.read(buf);

            // Check if too much data read, that this is the real url already
            if (len == 1024) {
                return trailerUrl;
            }

            String mov = new String(buf);

            int pos = 44;
            StringBuilder realUrl = new StringBuilder();

            while (mov.charAt(pos) != 0) {
                realUrl.append(mov.charAt(pos));

                pos++;
            }

            return getAbsUrl(trailerUrl, realUrl.toString());
        }
    } catch (IOException ex) {
        LOG.error("Error : {}", ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
        return Movie.UNKNOWN;
    }
}

From source file:GoogleAPI.java

/**
 * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
 * //from  w  w w . j  ava  2  s. c o m
 * @param url The URL to query for a JSONObject.
 * @param parameters Additional POST parameters
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);

        final PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.write(parameters);
        pw.close();
        uc.getOutputStream().close();

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            if (uc.getInputStream() != null) {
                uc.getInputStream().close();
            }
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
            if (pw != null) {
                pw.close();
            }
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:Main.java

public static void connectAndSendHttp(ByteArrayOutputStream baos) {
    try {/*from w w  w  . j  a va 2s  .co  m*/

        URL url;
        url = new URL("http://10.0.2.2:8080");

        String charset = "UTF-8";

        HttpURLConnection conn;

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = conn.getOutputStream();
        output.write(baos.toByteArray());
        output.close();
        conn.getInputStream();

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

From source file:com.qsoft.components.gallery.utils.GalleryUtils.java

private static InputStream OpenHttpConnection(String strURL) throws IOException {
    InputStream inputStream = null;
    URL url = new URL(strURL);
    URLConnection conn = url.openConnection();

    try {//ww  w  .  jav  a  2 s . c  o  m
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        Log.e("error", ex.toString());
    }
    return inputStream;
}

From source file:com.android.nunes.sophiamobile.gsm.GcmSender.java

public static void enviar(String msg, String token) {

    try {//from   www.  j  a  va2 s. co  m
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", msg.trim());
        // Where to send GCM message.
        if (token != null) {
            jGcmData.put("to", token.trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static byte[] retrieveImageData_fromUrl(String imageUrl) throws IOException {
    URL url = new URL(imageUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");

    // determine the image size and allocate a buffer
    int fileSize = connection.getContentLength();
    byte[] imageData = new byte[fileSize];

    // download the file
    Log.d(TAG, "fetching image " + imageUrl + " (" + fileSize + ")");

    if (fileSize > 0) {

        BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());
        int bytesRead = 0;
        int offset = 0;
        while (bytesRead != -1 && offset < fileSize) {
            bytesRead = istream.read(imageData, offset, fileSize - offset);
            offset += bytesRead;//from   w ww . ja  va  2 s. c o m
        }

        istream.close();
    } else
        Log.d(TAG, "fileSize is 0! skipping");

    // clean up
    connection.disconnect();

    return imageData;
}

From source file:com.edgenius.wiki.Shell.java

public static String requestSpaceThemeName(String spaceUname) {
    try {//w  ww.  j  a  v  a  2s.  c o m
        log.info("Request shell theme for space {}", spaceUname);

        //reset last keyValidator value  - will use new one.
        HttpURLConnection conn = (HttpURLConnection) new URL(getThemeRequestURL(spaceUname)).openConnection();
        conn.setConnectTimeout(timeout);
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        int len;
        byte[] bytes = new byte[200];
        while ((len = is.read(bytes)) != -1) {
            writer.write(bytes, 0, len);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return new String(writer.toByteArray());
        }
    } catch (IOException e) {
        log.error("Unable to connect shell for theme name request", e);
    } catch (Throwable e) {
        log.error("Notify shell failure", e);
    }

    return null;
}

From source file:com.facebook.GraphResponse.java

@SuppressWarnings("resource")
static List<GraphResponse> fromHttpConnection(HttpURLConnection connection, GraphRequestBatch requests) {
    InputStream stream = null;//from  w  w  w  .  j  a  v  a  2 s  . c  om

    try {
        if (connection.getResponseCode() >= 400) {
            stream = connection.getErrorStream();
        } else {
            stream = connection.getInputStream();
        }

        return createResponsesFromStream(stream, connection, requests);
    } catch (FacebookException facebookException) {
        Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", facebookException);
        return constructErrorResponses(requests, connection, facebookException);
    } catch (JSONException exception) {
        Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception);
        return constructErrorResponses(requests, connection, new FacebookException(exception));
    } catch (IOException exception) {
        Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception);
        return constructErrorResponses(requests, connection, new FacebookException(exception));
    } catch (SecurityException exception) {
        Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception);
        return constructErrorResponses(requests, connection, new FacebookException(exception));
    } finally {
        Utility.closeQuietly(stream);
    }
}

From source file:cloudlens.parser.FileReader.java

public static InputStream fetchFile(String urlString) {
    try {//from ww  w  .j  a  v  a 2  s. c o m
        InputStream inputStream;
        URL url;
        if (urlString.startsWith("local:")) {
            final String path = urlString.replaceFirst("local:", "");
            inputStream = Files.newInputStream(Paths.get(path));
        } else if (urlString.startsWith("file:")) {
            url = new URL(urlString);
            inputStream = Files.newInputStream(Paths.get(url.toURI()));
        } else if (urlString.startsWith("http:") || urlString.startsWith("https:")) {
            url = new URL(urlString);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            final Matcher matcher = Pattern.compile("//([^@]+)@").matcher(urlString);
            if (matcher.find()) {
                final String encoding = Base64.getEncoder().encodeToString(matcher.group(1).getBytes());
                conn.setRequestProperty("Authorization", "Basic " + encoding);
            }
            conn.setRequestMethod("GET");
            inputStream = conn.getInputStream();
        } else {
            throw new CLException("supported protocols are: http, https, file, and local.");
        }
        return inputStream;
    } catch (IOException | URISyntaxException e) {
        throw new CLException(e.getMessage());
    }
}

From source file:de.Keyle.MyPet.api.Util.java

public static String readUrlContent(String address, int timeout) throws IOException {
    StringBuilder contents = new StringBuilder(2048);
    BufferedReader br = null;/*  w  w  w. j ava  2  s.c  o  m*/

    try {
        URL url = new URL(address);
        HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        huc.setConnectTimeout(timeout);
        huc.setReadTimeout(timeout);
        huc.setRequestMethod("GET");
        huc.connect();
        br = new BufferedReader(new InputStreamReader(huc.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            contents.append(line);
        }
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return contents.toString();
}