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:com.ecarride.App.java

public static JSONArray loadJson(String url) throws JSONException {
    StringBuilder json = new StringBuilder();
    try {//w ww  .ja  v a  2s  .  c  o m
        URL urlObject = new URL(url);
        URLConnection uc = urlObject.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));

        String inputLine = null;
        //         int count = 0;
        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
            /*if (count++ <= 2)
               System.out.println(inputLine);*/
        }
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new JSONArray(json.toString());
}

From source file:com.deque.axe.AXE.java

/**
 * @return Contents of the axe.js or axe.min.js script with a configured reporter.
 *///from  w  ww .j av  a2  s  .  c o  m
private static String getContents(final URL script) {
    final StringBuilder sb = new StringBuilder();
    BufferedReader reader = null;

    try {
        URLConnection connection = script.openConnection();
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;

        while ((line = reader.readLine()) != null) {
            sb.append(line);
            sb.append(lineSeparator);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignored) {
            }
        }
    }

    return sb.toString();
}

From source file:disko.utils.GoogleLanguageDetector.java

/**
 * Returns the language code (en, ja, es, pt, etc.) for the language of the given String,
 * or null if the detection failed or was considered unreliable. 
 *  /*  w ww .  j  av a 2s .c o m*/
 * @param text
 * @return the language code
 */
public static String detectLanguage(String text) {

    String language = null;

    try {
        String encoded = URLEncoder.encode(text, "UTF-8");
        URL url = new URL(GOOGLE_LANGUAGE_DETECT_URL + encoded);
        URLConnection connection = DiscoProxySettings.newConnection(url);

        connection.addRequestProperty("Referer", DEFAULT_REFERRER);

        String line;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        JSONObject json = new JSONObject(builder.toString());
        log.debug("Answer for '" + text + "' :" + json);

        JSONObject responseData = json.getJSONObject("responseData");
        double confidence = responseData.getDouble("confidence");
        boolean isReliable = responseData.getBoolean("isReliable");

        language = responseData.getString("language");

        log.debug("Language " + language + "\tConfidence: " + confidence + "\tisReliable:" + isReliable);

        return (isReliable && language.length() > 0) ? language : null;

    } catch (Exception e) {
        log.error("Error detecting language of '" + text + "'", e);
        return null;
    }
}

From source file:com.taobao.diamond.server.controller.CheckController.java

public static String url2str(String sURL, String encoding) {
    try {/*  w w  w . ja v  a 2 s  .co m*/
        URL url = new URL(sURL);
        URLConnection conn = url.openConnection();
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpUrl = (HttpURLConnection) conn;
            httpUrl.getResponseCode();
        }
        InputStream is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
        String r = "";
        char[] cbuf = new char[1024];
        while (br.read(cbuf) > 0) {
            r += new String(cbuf);
        }
        return r;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.vexelon.bgrates.Utils.java

/**
 * Downloads a file given URL to specified destination
 * @param url/*from  w w  w  .j a  v  a  2s .  c  o m*/
 * @param destFile
 * @return
 */
//public static boolean downloadFile(Context context, String url, String destFile) {
public static boolean downloadFile(Context context, String url, File destFile) {
    //Log.v(TAG, "@downloadFile()");
    //Log.d(TAG, "Downloading " + url);

    boolean ret = false;

    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    InputStream is = null;

    try {
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();

        is = connection.getInputStream();
        bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(1024);

        int n = 0;
        while ((n = bis.read()) != -1)
            baf.append((byte) n);

        // save to internal storage
        //Log.v(TAG, "Saving downloaded file ...");
        fos = new FileOutputStream(destFile);
        //context.openFileOutput(destFile, context.MODE_PRIVATE);
        fos.write(baf.toByteArray());
        fos.close();
        //Log.v(TAG, "File saved successfully.");

        ret = true;
    } catch (Exception e) {
        //Log.e(TAG, "Error while downloading and saving file !", e);
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
        try {
            if (bis != null)
                bis.close();
        } catch (IOException e) {
        }
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
    }

    return ret;
}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static ImageLabel getImage(int id, String name) {
    try {/*  ww w  .  j  a v a 2s  . c om*/
        // logic for user verification

        //      Client client = ClientBuilder.newBuilder().newClient();
        //            WebTarget target = client.target("http://94.156.77.61:8080/photoshare");
        //            target = target.path("rest/image/getfile/MiltonStapler.jpg");
        //
        //            Invocation.Builder builder = target.request();
        //            Response response = builder.get();
        //            FileInputStream book = builder.get(FileInputStream.class);
        //            System.out.println("done");
        ProjectProperties props = new ProjectProperties();
        String webPage = "http://" + props.get("socket") + props.get("restEndpoint") + "/image/getfile/" + name;
        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());
        InputStream is = urlConnection.getInputStream();
        //            InputStreamReader isr = new InputStreamReader(is);
        //            
        //            int numCharsRead;
        //            char[] charArray = new char[1024];
        //            StringBuffer sb = new StringBuffer();
        //            while ((numCharsRead = isr.read(charArray)) > 0) {
        //                sb.append(charArray, 0, numCharsRead);
        //            }
        //            String result = sb.toString();
        BufferedImage bi = ImageIO.read(is);
        ImageLabel img = new ImageLabel(bi, id, name);
        return img;

        //            System.out.println("*** BEGIN ***");
        //            System.out.println(result);
        //            System.out.println("*** END ***");
    } catch (MalformedURLException ex) {
        Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.apache.clerezza.platform.testing.blackbox.osgi.FelixClerezzaPlatformTest.java

private static byte[] requestUrl(URL url) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    URLConnection urlConnection = url.openConnection();
    InputStream in = urlConnection.getInputStream();
    for (int ch = in.read(); ch != -1; ch = in.read()) {
        baos.write(ch);/*from  w w  w  . ja  v a2s .  c o m*/
    }
    return baos.toByteArray();
}

From source file:co.marcin.novaguilds.util.StringUtils.java

public static String getContent(String s) throws IOException {
    URL url = new URL(s);
    URLConnection con = url.openConnection();
    InputStream in = con.getInputStream();
    String encoding = con.getContentEncoding();
    encoding = encoding == null ? "UTF-8" : encoding;
    return IOUtils.toString(in, encoding);
}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static ArrayList<ImageLabel> getImages() {
    ProjectProperties props = new ProjectProperties();
    String webPage = "http://" + props.get("socket") + props.get("restEndpoint") + "/image";
    URL url;//from w ww.  j a v  a 2  s  . c  o  m
    try {
        url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());
        InputStream is = urlConnection.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
        Gson gson = new Gson();

        RemoteImage[] remoteImages = gson.fromJson(result, RemoteImage[].class);

        ArrayList<ImageLabel> images = new ArrayList<ImageLabel>();
        Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        for (RemoteImage rimg : remoteImages) {
            ImageLabel img = getImage(rimg.id, rimg.fileName);
            int imageWidth = img.getImage().getWidth(null);
            int imageHeight = img.getImage().getHeight(null);
            // just a relative estimation
            int imagesPerColumn = (int) Math.floor(Math.sqrt(Pagination.getImagesPerPage()));
            double ratio = (screenSize.height / (double) imageHeight < screenSize.width / (double) imageWidth)
                    ? screenSize.height / (double) imageHeight
                    : screenSize.width / (double) imageWidth;
            ratio = ratio / imagesPerColumn; // reduce ratio because more than 1 image are located in the column
            int resizeWidth = (int) (imageWidth * ratio);
            int resizeHeight = (int) (imageHeight * ratio);
            Image resizedImage = createResizedCopy(img.getImage(), resizeWidth, resizeHeight, false);
            images.add(new ImageLabel(resizedImage, img.getImageId(), img.getFileName()));
        }
        return images;
    } catch (MalformedURLException ex) {
        System.out.println(ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }

    return null;
}

From source file:it.imtech.configuration.ChooseServer.java

/**
 * Connection serrver test, acquiring certificate if exists.
 * @param uri - Selected server URI//ww w .j  a v  a 2  s  . co m
 * @return 
 */
public static boolean testServerConnection(String uri) {
    Server s = (Server) choose_server.getSelectedItem();

    boolean result = true;
    String outputFile = Globals.USER_DIR + "certs" + Utility.getSep() + "jssecacerts.jks";

    //Aggiungo Keystore Temporaneo
    if (new File(outputFile).isFile()) {
        System.setProperty("javax.net.ssl.keyStore", outputFile);
        System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
        System.setProperty("javax.net.ssl.trustStore", outputFile);
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    }

    try {
        URL url = new URL("https://" + uri);
        URLConnection con = url.openConnection();
        Reader reader = new InputStreamReader(con.getInputStream());
    } catch (SSLHandshakeException ex) {
        ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE,
                Globals.loader);
        Object[] options = { Utility.getBundleString("voc1", bundle), Utility.getBundleString("voc2", bundle) };

        int n = JOptionPane.showOptionDialog(null, Utility.getBundleString("phcertadd", bundle),
                Utility.getBundleString("phcertadd", bundle), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

        if (n == JOptionPane.YES_OPTION) {
            String[] run = new String[1];
            run[0] = uri + ":443";
            AddToStoreKey.createAndShowGUI(run);
            result = false;
        }
    } catch (Exception ex) {
    }

    return result;
}