Example usage for java.net URLConnection getContent

List of usage examples for java.net URLConnection getContent

Introduction

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

Prototype

public Object getContent() throws IOException 

Source Link

Document

Retrieves the contents of this URL connection.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    String urlString = "http://google.com";
    CookieManager manager = new CookieManager();
    CookieHandler.setDefault(manager);
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    Object obj = connection.getContent();
    url = new URL(urlString);
    connection = url.openConnection();//from  ww  w. j  a v  a2 s  . c o m
    obj = connection.getContent();
    CookieStore cookieJar = manager.getCookieStore();
    List<HttpCookie> cookies = cookieJar.getCookies();
    for (HttpCookie cookie : cookies) {
        System.out.println(cookie);
    }
}

From source file:FetchCookie.java

public static void main(String args[]) throws Exception {
    String urlString = "http://java.sun.com";
    CookieManager manager = new CookieManager();
    CookieHandler.setDefault(manager);
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    Object obj = connection.getContent();
    url = new URL(urlString);
    connection = url.openConnection();/* w w  w . j a v a 2s.  co  m*/
    obj = connection.getContent();
    CookieStore cookieJar = manager.getCookieStore();
    List<HttpCookie> cookies = cookieJar.getCookies();
    for (HttpCookie cookie : cookies) {
        System.out.println(cookie);
    }
}

From source file:Fetch5.java

  public static void main(String args[]) throws Exception {
  String urlString = "java.sun.com";
  CookieHandler.setDefault(new ListCookieHandler());
  URL url = new URL(urlString);
  URLConnection connection = url.openConnection();
  Object obj = connection.getContent();
  url = new URL(urlString);
  connection = url.openConnection();/*  w  w w. j  a  v a 2s.  co m*/
  obj = connection.getContent();
}

From source file:OldExtractor.java

/**
 * @param args the command line arguments
 *//*from  ww  w . j  a v  a2 s.c o  m*/
public static void main(String[] args) {
    // TODO code application logic here
    String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?$top=10&$format=Atom&Query=%27gates%27";
    //Provide your account key here.
    String accountKey = "ghTYY7wD6LpyxUO9VRR7e1f98WFhHWYERMcw87aQTqQ";
    //  String accountKey = "xqbCjT87/MQz25JWdRzgMHdPkGYnOz77IYmP5FUIgC8";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);

    try {
        URL url = new URL(bingUrl);
        URLConnection urlConnection = url.openConnection();

        urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        InputStream inputStream = (InputStream) urlConnection.getContent();
        byte[] contentRaw = new byte[urlConnection.getContentLength()];
        inputStream.read(contentRaw);
        String content = new String(contentRaw);
        //System.out.println(content);
        try {
            File file = new File("Results.xml");
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(content);
            //fileWriter.write("a test");
            fileWriter.flush();
            fileWriter.close();

        } catch (IOException e) {
            System.out.println(e);
        }

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            //System.out.println("here");
            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            //parse using builder to get DOM representation of the XML file
            Document dom = db.parse("Results.xml");
            Element docEle = (Element) dom.getDocumentElement();

            //get a nodelist of elements

            NodeList nl = docEle.getElementsByTagName("d:Url");
            if (nl != null && nl.getLength() > 0) {
                for (int i = 0; i < nl.getLength(); i++) {

                    //get the employee element
                    Element el = (Element) nl.item(i);
                    // System.out.println("here");
                    System.out.println(el.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }
            NodeList n2 = docEle.getElementsByTagName("d:Title");
            if (n2 != null && n2.getLength() > 0) {
                for (int i = 0; i < n2.getLength(); i++) {

                    //get the employee element
                    Element e2 = (Element) n2.item(i);
                    // System.out.println("here");
                    System.out.println(e2.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

            NodeList n3 = docEle.getElementsByTagName("d:Description");
            if (n3 != null && n3.getLength() > 0) {
                for (int i = 0; i < n3.getLength(); i++) {

                    //get the employee element
                    Element e3 = (Element) n3.item(i);
                    // System.out.println("here");
                    System.out.println(e3.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pe) {
            pe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } catch (IOException e) {
        System.out.println(e);
    }

    //The content string is the xml/json output from Bing.

}

From source file:com.netsteadfast.greenstep.util.WsServiceUtils.java

public static boolean testConnection(String wsdlAddress) throws Exception {
    if (StringUtils.isBlank(wsdlAddress)) {
        return true;
    }/*from  w ww  . java 2  s  . c om*/
    boolean status = false;
    try {
        URL url = new URL(wsdlAddress);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(TIMEOUT);
        connection.setReadTimeout(TIMEOUT);
        if (connection.getContent() != null) {
            status = true;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return status;
}

From source file:com.tweetlanes.android.core.URLFetch.java

public static void fetchBitmap(final String urlAsString, final FetchBitmapCallback callback) {

    Thread t = new Thread() {

        public void run() {
            URL url;//  w w w  . j  ava2 s  .c  o  m
            Bitmap bitmap = null;
            try {
                url = new URL(urlAsString);
                // Log.d("tweetlanes url fetch", urlAsString);
                URLConnection connection = url.openConnection();
                connection.setUseCaches(true);
                Object response = connection.getContent();
                if (response instanceof Bitmap) {
                    bitmap = (Bitmap) response;
                } else {
                    InputStream inputStream = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (callback != null) {
                callback.finished(bitmap != null ? true : false, bitmap);
            }
        }
    };
    t.start();
}

From source file:com.shafiq.mytwittle.URLFetch.java

public static void fetchBitmap(final String urlAsString, final FetchBitmapCallback callback) {

    Thread t = new Thread() {

        @Override// www  .jav  a 2 s .co m
        public void run() {
            URL url;
            Bitmap bitmap = null;
            try {
                url = new URL(urlAsString);
                // Log.d("mytwittle url fetch", urlAsString);
                URLConnection connection = url.openConnection();
                connection.setUseCaches(true);
                Object response = connection.getContent();
                if (response instanceof Bitmap) {
                    bitmap = (Bitmap) response;
                } else {
                    InputStream inputStream = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (callback != null) {
                callback.finished(bitmap != null ? true : false, bitmap);
            }
        }
    };
    t.start();
}

From source file:com.tweetlanes.android.URLFetch.java

public static void fetchBitmap(final String urlAsString, final FetchBitmapCallback callback) {

    Thread t = new Thread() {
        public void run() {
            URL url;// ww w  .j  av  a  2 s .  co  m
            Bitmap bitmap = null;
            try {
                url = new URL(urlAsString);
                //Log.d("tweetlanes url fetch", urlAsString);
                URLConnection connection = url.openConnection();
                connection.setUseCaches(true);
                Object response = connection.getContent();
                if (response instanceof Bitmap) {
                    bitmap = (Bitmap) response;
                } else {
                    InputStream inputStream = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (callback != null) {
                callback.finished(bitmap != null ? true : false, bitmap);
            }
        }
    };
    t.start();
}

From source file:tr.com.serkanozal.jcommon.util.ClasspathUtil.java

private static Set<URL> findClasspathUrls() {
    Set<URL> urls = new HashSet<URL>();

    try {/*from   w  w  w.j  av a2  s .  c  om*/
        String[] classpathProperties = System.getProperty("java.class.path").split(File.pathSeparator);
        for (String classpathProperty : classpathProperties) {
            urls.add(new File(classpathProperty).toURI().toURL());
        }
    } catch (MalformedURLException e) {
        logger.error("Error occured while getting classpath from system property \"java.class.path\"", e);
    }

    String surefireProperty = System.getProperty("surefire.test.class.path");
    if (StringUtils.isNotEmpty(surefireProperty)) {
        try {
            String[] surefireClasspathProperties = surefireProperty.split(File.pathSeparator);
            for (String surefireClasspathProperty : surefireClasspathProperties) {
                urls.add(new File(surefireClasspathProperty).toURI().toURL());
            }
        } catch (MalformedURLException e) {
            logger.error(
                    "Error occured while getting classpath from system property \"surefire.test.class.path\"",
                    e);
        }
    }

    // Start with Current Thread's loader
    ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader loader = ctxLoader;
    while (loader != null) {
        urls.addAll(findClasspathsByLoader(loader));
        loader = loader.getParent();
    }

    // Also start with this classes's loader, in some environment this can
    // be different than the current thread's one
    ClassLoader appLoader = ClasspathUtil.class.getClassLoader();
    loader = appLoader;
    while (loader != null) {
        urls.addAll(findClasspathsByLoader(loader));
        loader = loader.getParent();
    }

    ClassLoader sysLoader = ClassLoader.getSystemClassLoader();
    loader = sysLoader;
    while (loader != null) {
        urls.addAll(findClasspathsByLoader(loader));
        loader = loader.getParent();
    }

    Map<URL, URL> replaceURLs = new HashMap<URL, URL>();
    Set<URL> derivedUrls = new HashSet<URL>();
    for (URL url : urls) {
        if (url.getProtocol().startsWith("vfs")) {
            try {
                URLConnection conn = url.openConnection();
                Object virtualFile = conn.getContent();
                if (virtualFile.getClass().getName().equals("org.jboss.vfs.VirtualFile")) {
                    File file = (File) virtualFile.getClass().getMethod("getPhysicalFile").invoke(virtualFile);
                    String fileName = file.getCanonicalPath();
                    String name = (String) virtualFile.getClass().getMethod("getName").invoke(virtualFile);
                    name = name.trim().toLowerCase();
                    if ((name.endsWith("jar") || name.endsWith("zip") && fileName.endsWith("/contents"))) {
                        fileName = fileName.replace("contents", name);
                    }
                    URL repURL = new URL("file:/" + fileName);
                    replaceURLs.put(url, repURL);
                }
            } catch (Exception e) {
                // We don't expect to trapped here
                e.printStackTrace();
            }
        }
        try {
            if (url.toExternalForm().endsWith("WEB-INF/classes")) {
                derivedUrls.add(new URL(url.toExternalForm().replace("WEB-INF/classes", "WEB-INF/lib")));
            } else if (url.toExternalForm().endsWith("WEB-INF/classes/")) {
                derivedUrls.add(new URL(url.toExternalForm().replace("WEB-INF/classes/", "WEB-INF/lib/")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    urls.removeAll(replaceURLs.keySet());
    urls.addAll(replaceURLs.values());
    urls.addAll(derivedUrls);
    replaceURLs.clear();
    //Check contained urls
    for (URL url : urls) {
        for (URL rootUrl : urls) {
            if (url.equals(rootUrl)) {
                continue;
            }
            if (url.toExternalForm().startsWith(rootUrl.toExternalForm())) {
                if (replaceURLs.get(url) != null) {
                    URL settledUrl = replaceURLs.get(url);
                    if (settledUrl.toExternalForm().startsWith(rootUrl.toExternalForm())) {
                        replaceURLs.put(url, rootUrl);
                    }
                } else {
                    replaceURLs.put(url, rootUrl);
                }
            }
        }
    }
    urls.removeAll(replaceURLs.keySet());
    return urls;
}

From source file:de.quadrillenschule.azocamsyncd.astromode.SmartPhoneWrapper.java

public static SmartPhoneStatus remove(PhotoSerie ps) throws IOException {

    lastStatus = SmartPhoneStatus.TRYING;
    URL url;/*from  w ww  .  ja v  a 2 s .co m*/
    String retval;
    try {
        url = new URL(PROTOCOL + "://" + LAST_WORKING_IP + ":" + PORT + "/" + WebService.WebCommands.removejob
                + "/?" + WebService.WebParameters.jobid + "=" + ps.getId());
        System.out.println("Trying " + url.toString());
        URLConnection uc = url.openConnection();
        uc.setConnectTimeout(3000);
        StringWriter sw = new StringWriter();
        IOUtils.copy((InputStream) uc.getContent(), System.out);

    } catch (MalformedURLException ex) {
        Logger.getLogger(SmartPhoneWrapper.class.getName()).log(Level.SEVERE, null, ex);
        return SmartPhoneStatus.ERROR;

    }
    return SmartPhoneStatus.CONNECTED;
}