Example usage for java.net URLConnection connect

List of usage examples for java.net URLConnection connect

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:mc.lib.network.NetworkHelper.java

public static String getAsText(String url, String encoding) {
    InputStream is = null;/*w w w  .  ja  va 2  s  . com*/
    try {
        URLConnection c = new URL(url).openConnection();
        c.connect();
        is = c.getInputStream();
        if (c.getContentEncoding() != null)
            encoding = c.getContentEncoding();
        return StreamHelper.readNetworkStream(is, encoding, c.getReadTimeout());
    } catch (MalformedURLException e) {
        Log.e(LOGTAG, "Wrong url format", e);
    } catch (Exception e) {
        Log.e(LOGTAG, "Cannot get text", e);
    } finally {
        StreamHelper.close(is);
    }
    return null;
}

From source file:com.wishlist.Utility.java

public static Bitmap getBitmap(String url) {
    Bitmap bm = null;/*from   ww w. ja  va 2 s  . co m*/
    try {

        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
        bis.close();
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
    return bm;
}

From source file:com.example.facebook_photo.Utility.java

public static Bitmap getBitmap(String url) {
    Bitmap bm = null;/*from ww  w .j  a v  a 2 s  .c om*/
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
        bis.close();
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
    return bm;
}

From source file:ubic.gemma.core.loader.entrez.EutilFetch.java

private static Document parseSUrlInputStream(URL url)
        throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilder builder = EutilFetch.factory.newDocumentBuilder();
    int tries = 0;

    while (true) {
        URLConnection conn = url.openConnection();
        conn.connect();
        try (InputStream is = conn.getInputStream()) {
            return builder.parse(is);
        } catch (IOException e) {
            tries = EutilFetch.tryAgainOrFail(tries, e);
        }//ww  w . j a  v a  2 s  . c o m
    }
}

From source file:co.alligo.toasted.routes.Announce.java

public static boolean checkGameServer(String ip, String port) {
    boolean result;
    URL url;/*ww  w .  j a v a2  s . c o  m*/
    URLConnection urlConnection;
    DataInputStream dis;

    try {
        url = new URL("http://" + ip + ":" + port + "/");

        urlConnection = url.openConnection();
        urlConnection.connect();

        result = true;
    } catch (IOException ioe) {
        result = false;
    }
    return result;
}

From source file:net.amigocraft.mpt.command.InstallCommand.java

@SuppressWarnings("unchecked")
public static void downloadPackage(String id) throws MPTException {
    JSONObject packages = (JSONObject) Main.packageStore.get("packages");
    if (packages != null) {
        JSONObject pack = (JSONObject) packages.get(id);
        if (pack != null) {
            if (pack.containsKey("name") && pack.containsKey("version") && pack.containsKey("url")) {
                if (pack.containsKey("sha1") || !Config.ENFORCE_CHECKSUM) {
                    String name = pack.get("name").toString();
                    String version = pack.get("version").toString();
                    String fullName = name + " v" + version;
                    String url = pack.get("url").toString();
                    String sha1 = pack.containsKey("sha1") ? pack.get("sha1").toString() : "";
                    if (pack.containsKey("installed")) { //TODO: compare versions
                        throw new MPTException(ID_COLOR + name + ERROR_COLOR + " is already installed");
                    }//from   w w w. j  av a2 s . c o m
                    try {
                        URLConnection conn = new URL(url).openConnection();
                        conn.connect();
                        ReadableByteChannel rbc = Channels.newChannel(conn.getInputStream());
                        File file = new File(Main.plugin.getDataFolder(),
                                "cache" + File.separator + id + ".zip");
                        file.setReadable(true, false);
                        file.setWritable(true, false);
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                        FileOutputStream os = new FileOutputStream(file);
                        os.getChannel().transferFrom(rbc, 0, MiscUtil.getFileSize(new URL(url)));
                        os.close();
                        if (!sha1.isEmpty() && !sha1(file.getAbsolutePath()).equals(sha1)) {
                            file.delete();
                            throw new MPTException(ERROR_COLOR + "Failed to install package " + ID_COLOR
                                    + fullName + ERROR_COLOR + ": checksum mismatch!");
                        }
                    } catch (IOException ex) {
                        throw new MPTException(
                                ERROR_COLOR + "Failed to download package " + ID_COLOR + fullName);
                    }
                } else
                    throw new MPTException(ERROR_COLOR + "Package " + ID_COLOR + id + ERROR_COLOR
                            + " is missing SHA-1 checksum! Aborting...");
            } else
                throw new MPTException(ERROR_COLOR + "Package " + ID_COLOR + id + ERROR_COLOR
                        + " is missing required elements!");
        } else
            throw new MPTException(ERROR_COLOR + "Cannot find package with id " + ID_COLOR + id);
    } else {
        throw new MPTException(ERROR_COLOR + "Package store is malformed!");
    }
}

From source file:org.talend.mdm.bulkload.client.BulkloadClientTest.java

private static boolean isServerRunning(String serverURL) {
    boolean isServerRunning = false;
    try {//from www . j  a  v  a2 s . c om
        URL testURL = new URL(serverURL);
        URLConnection urlConnection = testURL.openConnection();
        urlConnection.connect();
        isServerRunning = true;
    } catch (IOException e) {
        System.out.println("Server is not running on '" + serverURL + "', skip this test.");
    }
    return isServerRunning;
}

From source file:org.kalypso.commons.java.net.UrlUtilities.java

/**
 * Tires to find a 'lastModified' timestamp from an {@link URL}.
 *///ww w .j a v  a  2  s  . co  m
public static Date lastModified(final URL location) {
    if (location == null)
        return null;

    try {
        final URLConnection connection = location.openConnection();
        connection.connect();

        final long lastModified = connection.getLastModified();
        // BUGFIX: some URLConnection implementations (such as eclipse resource-protokoll)
        // do not return lastModified correctly. If we have such a case, we try some more...
        if (lastModified != 0)
            return new Date(lastModified);

        final File file = FileUtils.toFile(location);
        if (file != null)
            return new Date(file.lastModified());

        final IPath path = ResourceUtilities.findPathFromURL(location);
        if (path == null)
            return null;

        final File resourceFile = ResourceUtilities.makeFileFromPath(path);
        return new Date(resourceFile.lastModified());
    } catch (final IOException e) {
        // ignore, some resources cannot be checked at all
    }

    return null;
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

private static boolean fileExistsOnServer(String URLName) {
    URL url;//from  ww  w .  j  a  va 2  s.co m
    try {
        url = new URL(URLName);
        URLConnection connection = url.openConnection();

        connection.connect();

        // Cast to a HttpURLConnection
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;

            int code = httpConnection.getResponseCode();

            if (code == 200)
                return true;
        } else {
            System.err.println("error - not a http request!");
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

private static Game readGameFromNet(String location) throws IOException, MalformedURLException {
    InputStream jsonInputStream;//from ww  w.j  av a 2 s .c o  m
    String prefix = "http://webcast-a.live.sportingpulseinternational.com/matches/";
    String suffix = "//data.json";
    String html_suffix = "//index.html";
    URL url = new URL(prefix + location + suffix);

    logger.log(Level.FINEST, "Downloading file {0} from internet", url.toString());
    URLConnection connection = url.openConnection();
    connection.connect();
    jsonInputStream = connection.getInputStream();

    try {
        Game game = readGameFromStream(jsonInputStream);
        try {
            URL html_url = new URL(prefix + location + html_suffix);
            String html = IOUtils.toString(html_url, "UTF-8");
            Matcher match = teamAndTime.matcher(html);
            if (match.matches()) {

                game.getTm().get(1).setTeam(match.group(1));
                game.getTm().get(2).setTeam(match.group(2));
                Calendar calendar = Calendar.getInstance(); //TimeZone.getTimeZone("EET")
                calendar.set(Integer.parseInt(match.group(7)), Integer.parseInt(match.group(6)) - 1,
                        Integer.parseInt(match.group(5)), Integer.parseInt(match.group(3)),
                        Integer.parseInt(match.group(4)));
                game.setDate(calendar.getTime());

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return game;
    } finally {
        jsonInputStream.close();
    }
}