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:com.ocp.media.UriTexture.java

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,
        ClientConnectionManager connectionManager) {
    InputStream contentInput = null;
    if (connectionManager == null) {
        try {/*from  w ww. j av  a  2  s  .c  o m*/
            URL url = new URI(uri).toURL();
            URLConnection conn = url.openConnection();
            conn.connect();
            contentInput = conn.getInputStream();
        } catch (Exception e) {
            Log.w(Gallery.TAG, TAG + ": " + "Request failed: " + uri);
            e.printStackTrace();
            return null;
        }
    } else {
        // We create a cancelable http request from the client
        final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS);
        HttpUriRequest request = new HttpGet(uri);
        // Execute the HTTP request.
        HttpResponse httpResponse = null;
        try {
            httpResponse = mHttpClient.execute(request);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                // Wrap the entity input stream in a GZIP decoder if
                // necessary.
                contentInput = entity.getContent();
            }
        } catch (Exception e) {
            Log.w(Gallery.TAG, TAG + ": " + "Request failed: " + request.getURI());
            return null;
        }
    }
    if (contentInput != null) {
        return new BufferedInputStream(contentInput, 4096);
    } else {
        return null;
    }
}

From source file:com.cooliris.media.UriTexture.java

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,
        ClientConnectionManager connectionManager) {
    InputStream contentInput = null;
    if (connectionManager == null) {
        try {// w  w w  . j a  v a2s  . c o  m
            URL url = new URI(uri).toURL();
            URLConnection conn = url.openConnection();
            conn.connect();
            contentInput = conn.getInputStream();
        } catch (Exception e) {
            Log.w(TAG, "Request failed: " + uri);
            e.printStackTrace();
            return null;
        }
    } else {
        // We create a cancelable http request from the client
        final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS);
        HttpUriRequest request = new HttpGet(uri);
        // Execute the HTTP request.
        HttpResponse httpResponse = null;
        try {
            httpResponse = mHttpClient.execute(request);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                // Wrap the entity input stream in a GZIP decoder if
                // necessary.
                contentInput = entity.getContent();
            }
        } catch (Exception e) {
            Log.w(TAG, "Request failed: " + request.getURI());
            return null;
        }
    }
    if (contentInput != null) {
        return new BufferedInputStream(contentInput, 4096);
    } else {
        return null;
    }
}

From source file:com.norconex.commons.lang.url.URLStreamer.java

private static InputStream responseInputStream(URLConnection conn) throws IOException {
    conn.connect();
    return new AutoCloseInputStream(conn.getInputStream());
}

From source file:io.teak.sdk.NotificationBuilder.java

public static Notification createNativeNotification(final Context context, Bundle bundle,
        TeakNotification teakNotificaton) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Rich text message
    Spanned richMessageText = Html.fromHtml(teakNotificaton.message);

    // Configure notification behavior
    builder.setPriority(NotificationCompat.PRIORITY_MAX);
    builder.setDefaults(NotificationCompat.DEFAULT_ALL);
    builder.setOnlyAlertOnce(true);//from   www.  j  av a 2  s . c o  m
    builder.setAutoCancel(true);
    builder.setTicker(richMessageText);

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    Random rng = new Random();

    // Create intent to fire if/when notification is cleared
    Intent pushClearedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_CLEARED_INTENT_ACTION_SUFFIX);
    pushClearedIntent.putExtras(bundle);
    PendingIntent pushClearedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(),
            pushClearedIntent, PendingIntent.FLAG_ONE_SHOT);
    builder.setDeleteIntent(pushClearedPendingIntent);

    // Create intent to fire if/when notification is opened, attach bundle info
    Intent pushOpenedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_OPENED_INTENT_ACTION_SUFFIX);
    pushOpenedIntent.putExtras(bundle);
    PendingIntent pushOpenedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(), pushOpenedIntent,
            PendingIntent.FLAG_ONE_SHOT);
    builder.setContentIntent(pushOpenedPendingIntent);

    // Because we can't be certain that the R class will line up with what is at SDK build time
    // like in the case of Unity et. al.
    class IdHelper {
        public int id(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "id", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.id." + identifier);
            }
            return ret;
        }

        public int layout(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "layout", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.layout." + identifier);
            }
            return ret;
        }
    }
    IdHelper R = new IdHelper(); // Declaring local as 'R' ensures we don't accidentally use the other R

    // Configure notification small view
    RemoteViews smallView = new RemoteViews(context.getPackageName(),
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_notif_no_title_v21")
                    : R.layout("teak_notif_no_title"));

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        smallView.setImageViewResource(R.id("left_image"), ai.icon);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    // Set small view text
    smallView.setTextViewText(R.id("text"), richMessageText);

    // Check for Jellybean (API 16, 4.1)+ for expanded view
    RemoteViews bigView = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && teakNotificaton.longText != null
            && !teakNotificaton.longText.isEmpty()) {
        bigView = new RemoteViews(context.getPackageName(),
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_big_notif_image_text_v21")
                        : R.layout("teak_big_notif_image_text"));

        // Set big view text
        bigView.setTextViewText(R.id("text"), Html.fromHtml(teakNotificaton.longText));

        URI imageAssetA = null;
        try {
            imageAssetA = new URI(teakNotificaton.imageAssetA);
        } catch (Exception ignored) {
        }

        Bitmap topImageBitmap = null;
        if (imageAssetA != null) {
            try {
                URL aURL = new URL(imageAssetA.toString());
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                topImageBitmap = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap == null) {
            try {
                InputStream istr = context.getAssets().open("teak_notif_large_image_default.png");
                topImageBitmap = BitmapFactory.decodeStream(istr);
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap != null) {
            // Set large bitmap
            bigView.setImageViewBitmap(R.id("top_image"), topImageBitmap);
        } else {
            Log.e(LOG_TAG, "Unable to load image asset for Notification.");
            // Hide pulldown
            smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
        }
    } else {
        // Hide pulldown
        smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
    }

    // Voodoo from http://stackoverflow.com/questions/28169474/notification-background-in-android-lollipop-is-white-can-we-change-it
    int topId = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    int topBigLayout = Resources.getSystem().getIdentifier("notification_template_material_big_media_narrow",
            "layout", "android");
    int topSmallLayout = Resources.getSystem().getIdentifier("notification_template_material_media", "layout",
            "android");

    RemoteViews topBigView = null;
    if (bigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // This is invisible inner view - to have media_actions in hierarchy
        RemoteViews innerTopView = new RemoteViews("android", topBigLayout);
        bigView.addView(android.R.id.empty, innerTopView);

        // This should be on top - we need status_bar_latest_event_content as top layout
        topBigView = new RemoteViews("android", topBigLayout);
        topBigView.removeAllViews(topId);
        topBigView.addView(topId, bigView);
    } else if (bigView != null) {
        topBigView = bigView;
    }

    // This should be on top - we need status_bar_latest_event_content as top layout
    RemoteViews topSmallView;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        topSmallView = new RemoteViews("android", topSmallLayout);
        topSmallView.removeAllViews(topId);
        topSmallView.addView(topId, smallView);
    } else {
        topSmallView = smallView;
    }

    builder.setContent(topSmallView);

    Notification n = builder.build();
    if (topBigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // Use reflection to avoid compile-time issues, we check minimum API version above
        try {
            Field bigContentViewField = n.getClass().getField("bigContentView");
            bigContentViewField.set(n, topBigView);
        } catch (Exception ignored) {
        }
    }

    return n;
}

From source file:org.wso2.carbon.apimgt.core.util.APIMWSDLUtils.java

/**
 * Retrieves the WSDL located in the provided URI ({@code wsdlUrl}
 *
 * @param wsdlUrl URL of the WSDL file//w  ww .  j  a  v a2  s.c  o  m
 * @return Content bytes of the WSDL file
 * @throws APIMgtWSDLException If an error occurred while retrieving the WSDL file
 */
public static byte[] getWSDL(String wsdlUrl) throws APIMgtWSDLException {
    ByteArrayOutputStream outputStream = null;
    InputStream inputStream = null;
    URLConnection conn;
    try {
        URL url = new URL(wsdlUrl);
        conn = url.openConnection();
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        conn.connect();

        outputStream = new ByteArrayOutputStream();
        inputStream = conn.getInputStream();
        IOUtils.copy(inputStream, outputStream);
        return outputStream.toByteArray();
    } catch (IOException e) {
        throw new APIMgtWSDLException("Error while reading content from " + wsdlUrl, e,
                ExceptionCodes.INVALID_WSDL_URL_EXCEPTION);
    } finally {
        if (outputStream != null) {
            IOUtils.closeQuietly(outputStream);
        }
        if (inputStream != null) {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

From source file:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Double getLycBtcRate() {
    try {//ww w .j  a  va  2 s .c o m
        final URL URL = new URL("http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=177");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);

            final JSONObject head = new JSONObject(content.toString());
            final JSONObject o = head.getJSONObject("return").getJSONObject("markets").getJSONObject("LYC");
            final Double rate = o.getDouble("lasttradeprice");
            if (rate != null)
                return rate;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java

/**
 * checks if GRIT can connect to the remote SVN server.
 *
 * @param svnRepoAdress/*from   ww w .  j a  va2  s.  c om*/
 *            the adress of the remote
 * @return true if GRIT can connect to the SVN.
 * @throws SubmissionFetchingException
 *             If the URL to the SVN is invalid.
 */
private static boolean checkConnectionToRemoteSVN(String svnRepoAdress) throws SubmissionFetchingException {
    try {
        int connectionTimeoutMillis = 10000;
        if (!svnRepoAdress.startsWith("file://")) {
            URL svnRepoLocation = new URL(svnRepoAdress);
            URLConnection svnRepoConnection = svnRepoLocation.openConnection();
            svnRepoConnection.setConnectTimeout(connectionTimeoutMillis);
            svnRepoConnection.connect();
        }
        return true;
    } catch (MalformedURLException e) {
        throw new SubmissionFetchingException(
                "Bad URL specified. Can not connect to this URL: " + svnRepoAdress + e.getMessage());
    } catch (IOException e) {
        return false;
    }
}

From source file:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {//from w  ww . j  av a  2s .c om
        final URL URL = new URL("https://blockchain.info/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                final Double drate = o.getDouble("15m") * LycBtcRate;
                String rate = String.format("%.8f", drate);
                rate = rate.replace(",", ".");
                if (rate != null)
                    rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate),
                            "cryptsy.com and " + URL.getHost()));
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:cl.tide.fm.sensonet.SensonetClient.java

public static boolean netIsAvailable() {
    try {//from  w  w  w . ja  v a  2 s . com
        final URL url = new URL(baseUrl);
        final URLConnection conn = url.openConnection();
        conn.connect();
        return true;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        return false;
    }
}

From source file:com.qhn.bhne.xhmusic.utils.MyUtils.java

public static BufferedInputStream getInputStream(String musicPicRes) {
    URL iconUrl = null;// w ww .  ja  v a 2 s . co m
    try {
        iconUrl = new URL(musicPicRes);
        URLConnection conn = iconUrl.openConnection();
        HttpURLConnection http = (HttpURLConnection) conn;

        int length = http.getContentLength();

        conn.connect();
        // ??
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), length);
        return bis;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}