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.kryten2k35.otaupdater.tasks.UpdateDownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    mContext = getApplicationContext();/*from   ww  w  .  j  a va2 s  .co  m*/
    if (DEBUGGING)
        Log.d(TAG, "DownloadService started");
    remoteFileInfo = UpdaterApplication.getRemoteFileInfo();
    String filename = remoteFileInfo.getFilename();
    String fileUrl = remoteFileInfo.getDirectUrl();

    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle(filename.replaceAll("/", ""))
            .setContentText(getString(R.string.download_in_progress)).setSmallIcon(R.drawable.ic_notification)
            .setOngoing(true);

    Intent progressIntent = new Intent(DOWNLOAD_PROGRESS);

    try {
        InputStream input = null;

        URL url = new URL(fileUrl);
        URLConnection connection = url.openConnection();
        connection.connect();

        int fileLength = connection.getContentLength();

        // download the file
        input = new BufferedInputStream(url.openStream());

        String downloadLocation = Preferences.getDownloadLocation(mContext);
        File dir = new File(downloadLocation);
        File file = new File(downloadLocation + filename);
        dir.mkdirs();
        FileOutputStream fOut = new FileOutputStream(file);

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        int percentDone = -1;

        if (DEBUGGING)
            Log.d(TAG, "DownloadService Downloading...");
        while ((count = input.read(data)) != -1 && !isCancelled) {
            total += count;
            // publishing the progress....
            int progress = (int) Math.round(total * 100 / fileLength);

            fOut.write(data, 0, count);

            if (percentDone != progress) {
                percentDone = progress;
                mBuilder.setProgress(100, progress, false);
                mNotifyManager.notify(0, mBuilder.build());
            }

            progressIntent.putExtra("progress", progress);
            progressIntent.putExtra("total", (int) total);
            sendBroadcast(progressIntent);
        }

        fOut.flush();
        fOut.close();
        input.close();
        mIsSuccessful = true;
    } catch (Exception e) {
        mIsSuccessful = false;
        Log.d(TAG, "Exception!", e);
    }

    if (mIsSuccessful) {
        if (isCancelled) {
            mBuilder.setContentText(getString(R.string.download_cancelled)).setProgress(0, 0, false)
                    .setOngoing(false);
            mNotifyManager.notify(0, mBuilder.build());
            sendBroadcast(new Intent(DOWNLOAD_CANCELLED));
        } else {
            mBuilder.setContentText(getString(R.string.download_complete)).setProgress(0, 0, false)
                    .setOngoing(false);
            mNotifyManager.notify(0, mBuilder.build());
            sendBroadcast(new Intent(DOWNLOAD_FINISHED));
        }
    }
}

From source file:com.sparkhunter.activities.FbfriendsActivity.java

public Bitmap getBitmap(String url) {
    AndroidHttpClient httpclient = null;
    Bitmap bm = null;// ww w .j  av  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:no.get.cms.plugin.resourcecompressor.ContentLoader.java

public String load(String srcUrl) {
    try {/*from w ww .  j a v a  2  s.c o m*/
        URL url = new URL(srcUrl);
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setConnectTimeout(2000);
        connection.setReadTimeout(10000);
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        String charset = extractCharsetFromContentType(connection.getContentType());
        String body = IOUtils.toString(inputStream, charset);
        IOUtils.close(connection);
        return body;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ar.com.martinrevert.argenteam.GcmIntentService.java

public Bitmap getRemoteImage(final String aURL, String tipo) {
    try {//  w w  w  .  ja  v  a  2 s. co m
        if (aURL.isEmpty()) {
            if (tipo.equals("movie")) {
                return BitmapFactory.decodeResource(this.getResources(), R.drawable.stubportrait);
            } else {

                return BitmapFactory.decodeResource(this.getResources(), R.drawable.stublandscape);

            }
        }
        URL imagelink = new URL(aURL);
        final URLConnection conn = imagelink.openConnection();
        conn.connect();
        final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        BitmapFactory.Options options = new BitmapFactory.Options();
        final Bitmap scaledBitmap = BitmapFactory.decodeStream(bis, null, options);
        bis.close();
        return scaledBitmap;
    } catch (IOException e) {
        e.printStackTrace();

    }
    return null;
}

From source file:com.pentaho.ctools.cdf.require.ExecuteXactionComponent.java

/**
 * ############################### Test Case 3 ###############################
 *
 * Test Case Name://from   w w  w.  j  a va  2s . c o m
 *    Execute Xacion
 * Description:
 *    We pretend validate the generated chart (in an image) and if the image
 *    has a valid url.
 * Steps:
 *    1. Click to generate chart
 *    2. Check if a chart was generated
 *    3. Check the http request for the image generated
 */
@Test
public void tc3_PressToGenerateChart_ChartIsDisplayed() {
    this.log.info("tc3_PressToGenerateChart_ChartIsDisplayed");

    /*
     *  ## Step 1
     */
    final String buttonName = this.elemHelper.WaitForElementPresentGetText(driver, By.xpath("//button/span"));
    assertEquals("Execute XAction", buttonName);
    //Click in button
    this.elemHelper.FindElement(driver, By.xpath("//button")).click();

    // ## Step 1
    wait.until(ExpectedConditions.presenceOfElementLocated(By.id("fancybox-content")));
    driver.switchTo().frame("fancybox-frame");
    //Check the title
    final String chartTitle = this.elemHelper.WaitForElementPresentGetText(driver,
            By.xpath("//table/tbody/tr/td"));
    assertEquals("Action Successful", chartTitle);
    //Check for the displayed image
    final WebElement xactionElement = this.elemHelper.FindElement(driver, By.cssSelector("img"));
    assertNotNull(xactionElement);

    final String attrSrc = xactionElement.getAttribute("src");
    final String attrWidth = xactionElement.getAttribute("width");
    final String attrHeight = xactionElement.getAttribute("height");

    assertTrue(attrSrc.startsWith(baseUrl + "getImage?image=tmp_chart_admin-"));
    assertEquals(attrWidth, "500");
    assertEquals(attrHeight, "600");

    // ## Step 3
    try {
        final URL url = new URL(attrSrc);
        final URLConnection connection = url.openConnection();
        connection.connect();

        assertEquals(HttpStatus.SC_OK, ((HttpURLConnection) connection).getResponseCode());
    } catch (final Exception ex) {
        this.log.error(ex.getMessage());
    }

    //Close pop-up window
    driver.switchTo().defaultContent();
    this.elemHelper.FindElement(driver, By.id("fancybox-close")).click();
    this.elemHelper.WaitForElementInvisibility(driver, By.id("fancybox-content"));
    assertNotNull(this.elemHelper.FindElement(driver, By.xpath("//button")));
}

From source file:org.kuali.mobility.itnotices.service.ITNoticesServiceImpl.java

private List<ITNotice> getITNoticesFromFeed() {
    List<ITNotice> notices = new ArrayList<ITNotice>();
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;// ww w  .ja v a 2s  .c  om
    URL urlObj;
    try {
        urlObj = new URL("http://itnotices.iu.edu/rss.aspx");
        URLConnection urlConnection = urlObj.openConnection();
        urlConnection.setConnectTimeout(5000);
        urlConnection.setReadTimeout(5000);
        urlConnection.connect();
        doc = builder.build(urlConnection.getInputStream());

        if (doc != null) {
            Element root = doc.getRootElement();
            List items = root.getChild("channel").getChildren("item");
            for (Iterator iterator = items.iterator(); iterator.hasNext();) {
                Element item = (Element) iterator.next();
                String services = "";
                List service = item.getChildren("service");
                for (Iterator iterator2 = service.iterator(); iterator2.hasNext();) {
                    Element s = (Element) iterator2.next();
                    services += s.getContent(0).getValue() + ", ";
                }
                if (services.endsWith(", ")) {
                    services = services.substring(0, services.length() - 2);
                }
                ITNotice notice = new ITNotice(item.getChildTextTrim("lastUpdated"),
                        item.getChildTextTrim("noticeType"), item.getChildTextTrim("title"), services,
                        item.getChildTextTrim("message"));
                determineImage(notice);
                notices.add(notice);
            }
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

    return notices;
}

From source file:BihuHttpUtil.java

/**
 * ?URL??GET/*from  w  ww  .java2 s . com*/
 *
 * @param url
 *            ??URL
 * @param param
 *            ?? name1=value1&name2=value2 ?
 * @return URL ??
 */
public static String sendGet(String url, String param) {
    String result = "";
    BufferedReader in = null;
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        // URL
        URLConnection connection = realUrl.openConnection();
        // 
        connection.setRequestProperty("Host", "quote.zhonghe-bj.com:8085");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        // 
        connection.connect();
        //  BufferedReader???URL?
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("??GET?" + e);
        e.printStackTrace();
    }
    // finally???
    finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
    return result;
}

From source file:uk.ac.sanger.cgp.dbcon.util.resources.UrlResource.java

protected InputStream getActualInputStream() {
    InputStream is = null;//from ww w  . ja va  2 s  .c  o m
    URLConnection connection = null;

    try {
        URL url = URI.create(getLocation()).toURL();
        connection = url.openConnection();
        connection.connect();
        InputStream bytesInput = connection.getInputStream();
        byte[] bytes = IOUtils.toByteArray(bytesInput);
        is = new ByteArrayInputStream(bytes);
    } catch (MalformedURLException e) {
        cleanUpHttpURLConnection(connection);
        throw new DbConException("Detected a malformed URL; aborting", e);
    } catch (FileNotFoundException e) {
        cleanUpHttpURLConnection(connection);
        throw new DbConException("Could not find the specified file at the given URL", e);
    } catch (IOException e) {
        cleanUpHttpURLConnection(connection);
        throw new DbConException("Detected IO problems whilst reading URL's content", e);
    }

    return is;
}

From source file:org.sensorhub.impl.sensor.axis.AxisCameraDriver.java

@Override
public boolean isConnected() {
    try {/*from  w w  w  .  ja  va 2s .com*/
        // try to open stream and check for AXIS Brand
        URL optionsURL = new URL(
                "http://" + ipAddress + "/axis-cgi/view/param.cgi?action=list&group=root.Brand.Brand");
        URLConnection conn = optionsURL.openConnection();
        conn.setConnectTimeout(500);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        // note: should return one line with root.Brand.Brand=AXIS
        String line = reader.readLine();
        if (line != null) {
            String[] tokens = line.split("=");
            if ((tokens[0].trim().equalsIgnoreCase("root.Brand.Brand"))
                    && (tokens[1].trim().equalsIgnoreCase("AXIS")))
                return true;
        }

        return false;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.github.bfour.fpliteraturecollector.service.FileStorageService.java

public Link persist(URL webAddress, Literature lit) throws IOException {

    String fileName = getFileNameForLiterature(lit);
    fileName += ".pdf";
    // + FilenameUtils.getExtension(webAddress.getFile()).substring(0,
    // 3);/*from  ww w  .ja va 2 s .c o m*/
    File file = new File(rootDirectory.getAbsolutePath() + "/" + lit.getID() + "/" + fileName);

    URLConnection conn = webAddress.openConnection();
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0");
    conn.connect();
    FileUtils.copyInputStreamToFile(conn.getInputStream(), file);

    return new Link(fileName, file.toURI(), webAddress.toString());

}