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:net.hockeyapp.android.tasks.CheckUpdateTask.java

@Override
protected JSONArray doInBackground(Void... args) {
    try {//from w w  w. ja v a2 s  . c  om
        int versionCode = getVersionCode();

        JSONArray json = new JSONArray(VersionCache.getVersionInfo(context));

        if ((getCachingEnabled()) && (findNewVersion(json, versionCode))) {
            HockeyLog.verbose("HockeyUpdate", "Returning cached JSON");
            return json;
        }

        URL url = new URL(getURLString("json"));
        URLConnection connection = createConnection(url);
        connection.connect();

        InputStream inputStream = new BufferedInputStream(connection.getInputStream());
        String jsonString = convertStreamToString(inputStream);
        inputStream.close();

        json = new JSONArray(jsonString);
        if (findNewVersion(json, versionCode)) {
            json = limitResponseSize(json);
            return json;
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.squale.welcom.addons.access.excel.UpdateAccessManager.java

/**
 * @param url : URL/*from  ww  w  .j ava 2 s.  c  om*/
 * @return La date de dernier emodification de l'url
 */
private Date getTimeUrl(final URL url) {
    try {
        final URLConnection urlCon = url.openConnection();
        urlCon.setUseCaches(false);
        urlCon.connect();
        return new Date(urlCon.getLastModified());
    } catch (final IOException e) {
        logStartup.error(e, e);
    }
    return null;
}

From source file:com.example.HelloLicenseServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    UserService userService = UserServiceFactory.getUserService();
    PrintWriter output = response.getWriter();
    String url = request.getRequestURI();

    if (userService.isUserLoggedIn()) {
        // Provide a logout path.
        User user = userService.getCurrentUser();
        output.printf("<strong>%s</strong> | <a href=\"%s\">Sign out</a><br><br>", user.getEmail(),
                userService.createLogoutURL(url));

        try {//from   w  ww. j ava 2  s .  c  om
            // Send a signed request for the user's license state.
            OAuthConsumer oauth = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
            oauth.setTokenWithSecret(TOKEN, TOKEN_SECRET);
            URLConnection http = new URL(
                    String.format(URL, APP_ID, URLEncoder.encode(user.getFederatedIdentity(), "UTF-8")))
                            .openConnection();
            oauth.sign(http);
            http.connect();

            // Convert the response from the license server to a string.
            BufferedReader input = new BufferedReader(new InputStreamReader(http.getInputStream()));
            String file = "";
            for (String line; (line = input.readLine()) != null; file += line)
                ;
            input.close();

            // Parse the string as JSON and display the license state.
            JSONObject json = new JSONObject(file);
            output.printf("Hello <strong>%s</strong> license!",
                    "YES".equals(json.get("result"))
                            ? "FULL".equals(json.get("accessLevel")) ? "full" : "free trial"
                            : "no");
        } catch (Exception exception) {
            // Dump any error.
            output.printf("Oops! <strong>%s</strong>", exception.getMessage());
        }
    } else { // The user isn't logged in.
        // Prompt for login.
        output.printf("<a href=\"%s\">Sign in</a>", userService.createLoginURL(url, null,
                "https://www.google.com/accounts/o8/id", new HashSet<String>()));
    }
}

From source file:com.amastigote.xdu.query.module.WaterAndElectricity.java

private void preLogin() throws IOException {
    URL url = new URL(HOST + PRE_LOGIN_SUFFIX);
    URLConnection urlConnection = url.openConnection();
    urlConnection.connect();
    String tmp = urlConnection.getHeaderField("Set-Cookie");

    ASP_dot_NET_SessionId = tmp.substring(tmp.indexOf("=") + 1, tmp.indexOf(";"));
}

From source file:org.b5chat.crossfire.web.FaviconServlet.java

private byte[] getImage(String url) {
    try {//from   w  w  w .j av a  2  s  .  c o  m
        // Try to get the fiveicon from the url using an HTTP connection from the pool
        // that also allows to configure timeout values (e.g. connect and get data)
        GetMethod get = new GetMethod(url);
        get.setFollowRedirects(true);
        int response = client.executeMethod(get);
        if (response < 400) {
            // Check that the response was successful. Should we also filter 30* code?
            return get.getResponseBody();
        } else {
            // Remote server returned an error so return null
            return null;
        }
    } catch (IllegalStateException e) {
        // Something failed (probably a method not supported) so try the old stye now
        try {
            URLConnection urlConnection = new URL(url).openConnection();
            urlConnection.setReadTimeout(1000);

            urlConnection.connect();
            DataInputStream di = new DataInputStream(urlConnection.getInputStream());

            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            DataOutputStream out = new DataOutputStream(byteStream);

            int len;
            byte[] b = new byte[1024];
            while ((len = di.read(b)) != -1) {
                out.write(b, 0, len);
            }
            di.close();
            out.flush();

            return byteStream.toByteArray();
        } catch (IOException ioe) {
            // We failed again so return null
            return null;
        }
    } catch (IOException ioe) {
        // We failed so return null
        return null;
    }
}

From source file:org.squale.welcom.struts.webServer.URLManager.java

/**
 * Retourn l'url a partie d'un site distant
 * /*from ww w .  j  a  v a  2 s  .c o m*/
 * @param pUrl url
 * @throws MalformedURLException problem sur l'url
 * @throws IOException exception
 * @return webfile
 */
private WebFile getWebFileFromHTTP(String pUrl) throws MalformedURLException, IOException {
    WebFile webFile = new WebFile(WebFile.TYPE_DISTANT);
    webFile.setUrl(new URL(pUrl));
    final URLConnection urlcon = webFile.getUrl().openConnection();
    urlcon.setUseCaches(true);
    urlcon.connect();
    webFile.setLastDate(new Date(urlcon.getLastModified()));

    if (urlcon.getLastModified() == 0) {
        webFile.setLastDate(new Date(urlcon.getDate()));
    }

    return webFile;
}

From source file:org.esupportail.pay.services.PayBoxService.java

protected String getPayBoxActionUrl() {
    for (String payboxActionUrl : payboxActionUrls) {
        try {/*  w  w  w .  java  2  s  . c  o m*/
            URL url = new URL(payboxActionUrl);
            URLConnection connection = url.openConnection();
            connection.connect();
            connection.getInputStream().read();
            return payboxActionUrl;
        } catch (Exception e) {
            log.warn("Pb with " + payboxActionUrl, e);
        }
    }
    throw new RuntimeException("No paybox action url is available at the moment !");
}

From source file:com.aptana.webserver.internal.core.builtin.LocalWebServer.java

private void testConnection(URL url) throws CoreException {
    CoreException exception = null;/*from  w  ww.j  a  va2  s .  c o m*/
    for (int trial = 0; trial < 3; ++trial) {
        try {
            URLConnection connection = url.openConnection(); // $codepro.audit.disable variableDeclaredInLoop
            connection.connect();
            connection.getContentType();
            return;
        } catch (IOException e) {
            exception = new CoreException(new Status(IStatus.ERROR, WebServerCorePlugin.PLUGIN_ID,
                    "Testing WebServer connection failed", e)); //$NON-NLS-1$
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            break;
        }
    }
    if (exception != null) {
        throw exception;
    }
}

From source file:eu.faircode.netguard.ServiceExternal.java

@Override
protected void onHandleIntent(Intent intent) {
    try {//w  w w  . j a  v a2s  .c om
        startForeground(ServiceSinkhole.NOTIFY_EXTERNAL, getForegroundNotification(this));

        Log.i(TAG, "Received " + intent);
        Util.logExtras(intent);

        if (ACTION_DOWNLOAD_HOSTS_FILE.equals(intent.getAction())) {
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

            String hosts_url = prefs.getString("hosts_url", null);
            File tmp = new File(getFilesDir(), "hosts.tmp");
            File hosts = new File(getFilesDir(), "hosts.txt");

            InputStream in = null;
            OutputStream out = null;
            URLConnection connection = null;
            try {
                URL url = new URL(hosts_url);
                connection = url.openConnection();
                connection.connect();

                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
                        throw new IOException(
                                httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage());
                }

                int contentLength = connection.getContentLength();
                Log.i(TAG, "Content length=" + contentLength);
                in = connection.getInputStream();
                out = new FileOutputStream(tmp);

                long size = 0;
                byte buffer[] = new byte[4096];
                int bytes;
                while ((bytes = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytes);
                    size += bytes;
                }

                Log.i(TAG, "Downloaded size=" + size);

                if (hosts.exists())
                    hosts.delete();
                tmp.renameTo(hosts);

                String last = SimpleDateFormat.getDateTimeInstance().format(new Date().getTime());
                prefs.edit().putString("hosts_last_download", last).apply();

                ServiceSinkhole.reload("hosts file download", this, false);

            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));

                if (tmp.exists())
                    tmp.delete();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (IOException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
                try {
                    if (in != null)
                        in.close();
                } catch (IOException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }

                if (connection instanceof HttpURLConnection)
                    ((HttpURLConnection) connection).disconnect();
            }
        }
    } finally {
        stopForeground(true);
    }
}

From source file:org.tupelo_schneck.electric.ted.ImportIterator.java

public ImportIterator(final Options options, final byte mtu, final int count) throws IOException {
    this.timeZone = options.recordTimeZone;
    this.cal = new GregorianCalendar(this.timeZone);
    this.mtu = mtu;
    this.useVoltage = options.voltage;
    URL url;// w  w  w. j a va 2s.  com
    try {
        url = new URL(
                options.gatewayURL + "/history/rawsecondhistory.raw?INDEX=1&MTU=" + mtu + "&COUNT=" + count);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    URLConnection urlConnection = url.openConnection();
    urlConnection.setConnectTimeout(60000);
    urlConnection.setReadTimeout(60000);
    urlConnection.connect();
    urlStream = urlConnection.getInputStream();
    urlConnection.setReadTimeout(1000);
    getNextLine();

    // skip the first timestamp, in case we see only part of multiple values
    if (!closed) {
        Triple first = nextFromLine();
        Triple next = first;
        while (next != null && next.timestamp == first.timestamp) {
            next = nextFromLine();
        }
        pushback = next;

        if (Util.inDSTOverlap(timeZone, first.timestamp)) {
            int now = (int) (System.currentTimeMillis() / 1000);
            if (now < first.timestamp - 1800)
                inDSTOverlap = 1;
            else
                inDSTOverlap = 2;
        }
        previousTimestamp = first.timestamp;
    }
}