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.heliosdecompiler.helios.bootloader.Bootloader.java

private static byte[] loadSWTLibrary() throws IOException, NoSuchMethodException, IllegalAccessException,
        InvocationTargetException, ClassNotFoundException {
    String name = getOSName();/*from ww  w .  j a v a 2  s  .  c o  m*/
    if (name == null)
        throw new IllegalArgumentException("Cannot determine OS");
    String arch = getArch();
    if (arch == null)
        throw new IllegalArgumentException("Cannot determine architecture");

    String artifactId = "org.eclipse.swt." + name + "." + arch;
    String swtLocation = artifactId + "-" + SWT_VERSION + ".jar";

    System.out.println("Loading SWT version " + swtLocation);

    byte[] data = null;

    File savedJar = new File(Constants.DATA_DIR, swtLocation);
    if (savedJar.isDirectory() && !savedJar.delete())
        throw new IllegalArgumentException("Saved file is a directory and could not be deleted");

    if (savedJar.exists() && savedJar.canRead()) {
        try {
            System.out.println("Loading from saved file");
            InputStream inputStream = new FileInputStream(savedJar);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            copy(inputStream, outputStream);
            data = outputStream.toByteArray();
        } catch (IOException exception) {
            System.out.println("Failed to load from saved file.");
            exception.printStackTrace(System.out);
        }
    }
    if (data == null) {
        InputStream fromJar = Bootloader.class.getResourceAsStream("/swt/" + swtLocation);
        if (fromJar != null) {
            try {
                System.out.println("Loading from within JAR");
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                copy(fromJar, outputStream);
                data = outputStream.toByteArray();
            } catch (IOException exception) {
                System.out.println("Failed to load within JAR");
                exception.printStackTrace(System.out);
            }
        }
    }
    if (data == null) {
        URL url = new URL("https://maven-eclipse.github.io/maven/org/eclipse/swt/" + artifactId + "/"
                + SWT_VERSION + "/" + swtLocation);
        try {
            System.out.println("Loading over the internet");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if (connection.getResponseCode() == 200) {
                InputStream fromURL = connection.getInputStream();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                copy(fromURL, outputStream);
                data = outputStream.toByteArray();
            } else {
                throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
            }
        } catch (IOException exception) {
            System.out.println("Failed to load over the internet");
            exception.printStackTrace(System.out);
        }
    }

    if (data == null) {
        throw new IllegalArgumentException("Failed to load SWT");
    }

    if (!savedJar.exists()) {
        try {
            System.out.println("Writing to saved file");
            if (savedJar.createNewFile()) {
                FileOutputStream fileOutputStream = new FileOutputStream(savedJar);
                fileOutputStream.write(data);
                fileOutputStream.close();
            } else {
                throw new IOException("Could not create new file");
            }
        } catch (IOException exception) {
            System.out.println("Failed to write to saved file");
            exception.printStackTrace(System.out);
        }
    }

    byte[] dd = data;

    URL.setURLStreamHandlerFactory(protocol -> { //JarInJar!
        if (protocol.equals("swt")) {
            return new URLStreamHandler() {
                protected URLConnection openConnection(URL u) {
                    return new URLConnection(u) {
                        public void connect() {
                        }

                        public InputStream getInputStream() {
                            return new ByteArrayInputStream(dd);
                        }
                    };
                }

                protected void parseURL(URL u, String spec, int start, int limit) {
                    // Don't parse or it's too slow
                }
            };
        }
        return null;
    });

    ClassLoader classLoader = Bootloader.class.getClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(classLoader, new URL("swt://load"));

    return data;
}

From source file:Main.java

public static String getResponse(String urlParam) {
    try {// w  w  w.  j a  v a  2s . c o m
        URL url = new URL(urlParam);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.1; SV1)");
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = conn.getInputStream();
            return inputStream2String(inputStream);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

From source file:com.easy.facebook.android.util.Util.java

public static byte[] loadPicture(String urlPicture) {
    byte[] pictureData = null;

    try {//from  w  ww.j  av a 2s.  c  om
        URL uploadFileUrl = null;
        try {
            uploadFileUrl = new URL(urlPicture);
        } catch (Exception e) {
            e.printStackTrace();
        }

        HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream fis = null;
        try {
            fis = conn.getInputStream();
        } catch (IOException e) {

            e.printStackTrace();
        }
        Bitmap bi = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        pictureData = baos.toByteArray();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    return pictureData;
}

From source file:Main.java

protected static String getResponseAsString(HttpURLConnection conn, boolean responseError) throws IOException {
    String charset = getResponseCharset(conn.getContentType());
    String header = conn.getHeaderField("Content-Encoding");
    boolean isGzip = false;
    if (header != null && header.toLowerCase().contains("gzip")) {
        isGzip = true;/*from   w  w w .  j ava 2 s . c  om*/
    }
    InputStream es = conn.getErrorStream();
    if (es == null) {
        InputStream input = conn.getInputStream();
        if (isGzip) {
            input = new GZIPInputStream(input);
        }
        return getStreamAsString(input, charset);
    } else {
        if (isGzip) {
            es = new GZIPInputStream(es);
        }
        String msg = getStreamAsString(es, charset);
        if (TextUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
        } else if (responseError) {
            return msg;
        } else {
            throw new IOException(msg);
        }
    }
}

From source file:Main.java

static String downloadUrl(String myurl) throws IOException {
    InputStream is = null;/* ww  w  .  j a v a2  s .c  o m*/

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "Basic cm9vdDpvcmllbnRkYg==");
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        //start
        conn.connect();
        int response = conn.getResponseCode();
        Log.e("The response is: ", "" + response);
        is = conn.getInputStream();
        //converte inputStream in stringa
        String contentAsString = readIt(is);
        return contentAsString;
    } catch (IOException e) {
        Log.e("HTTP", e.getMessage());
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.infosupport.service.LPRServiceCaller.java

public static JSONObject doGet(String urlString) {
    String json = null;//from  w  w w.  j  av a2s . c o  m
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

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

        String output;
        while ((output = br.readLine()) != null) {
            json = output;
            System.out.println(json + "from doGet");
        }
        conn.disconnect();
    } catch (IOException e) {
        Log.w(TAG, "IOException, waarschijnlijk geen internet connectie aanwezig...");
    }
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        Log.e(TAG, "Kon geen JsonObject maken van het response");
    }
    return jsonObject;
}

From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java

/**
 * Reads the data from a http call into a string.
 *//*w  w  w . j  a va 2  s  . c o  m*/
private static String readStringFromConnection(HttpURLConnection uc) throws IOException {
    InputStreamReader in = new InputStreamReader(uc.getInputStream());
    BufferedReader buff = new BufferedReader(in);
    StringBuffer sb = new StringBuffer();
    String line = null;
    do {
        line = buff.readLine();
        if (line != null)
            sb.append(line);
    } while (line != null);

    return sb.toString();
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

private static String sendDELETE(URL url, HttpURLConnection con) throws IOException {

    logger.log(Level.INFO, "Sending DELETE request to URL : {0}", url);
    int responseCode = con.getResponseCode();
    logger.log(Level.INFO, "Response Code : {0}", responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;//from   www . j a v a2  s.co  m
    StringBuilder responseStr = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        responseStr.append(inputLine);
    }
    in.close();

    return responseStr.toString();

}

From source file:com.arthurpitman.common.HttpUtils.java

/**
 * Retrieves a URL as a string./* ww w.  j  a v  a2s. co  m*/
 * @param url
 * @param requestProperties optional request properties, <code>null</code> if not required.
 * @param postData optional post data, <code>null</code> if not required.
 * @return a {@link String} representing the response.
 * @throws IOException
 */
public static String retrieveUrlAsString(final String url, final RequestProperty[] requestProperties,
        final byte[] postData) throws IOException {
    for (int i = 0;; i++) {
        HttpURLConnection connection = null;
        try {
            if (postData != null) {
                connection = connectPost(url, requestProperties, postData);
            } else {
                connection = connectGet(url, requestProperties);
            }
            return StreamUtils.readStreamIntoString(connection.getInputStream(), UTF8_CHARACTER_SET,
                    BUFFER_SIZE);
        } catch (IOException e) {
            if (i == CONNECTION_RETRIES) {
                throw e;
            }
        } finally {
            // always close the connection
            if (connection != null) {
                connection.disconnect();
            }
        }

        // allow recovery time
        try {
            Thread.sleep(CONNECTION_RETRY_SLEEP);
        } catch (InterruptedException e) {
        }
    }
}

From source file:Main.java

public static String openUrl(String url, String method, Bundle params) {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }//from   w  ww.  jav a2  s  .  co m
    String response = "";
    try {
        Log.d(LOG_TAG, method + " URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                System.getProperties().getProperty("http.agent") + " RenrenAndroidSDK");
        if (!method.equals("GET")) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }

        response = read(conn.getInputStream());
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        throw new RuntimeException(e.getMessage(), e);
    }
    return response;
}