0

How do I create a java.net.URL to refer to a CSS? Is it posible?

I've tried several other ways like this to check if its a css page but it doesn't work (no errors tho, but it doesn't):

        int code = con.getResponseCode();
        String type = con.getContentType();

        con.disconnect();

        //returns null if the connection had problems or its does not contain css
        if (code != HttpURLConnection.HTTP_OK || !type.contains("stylesheet")) {
            return null;
        }

Any other posible solutions? Basically what I try to do is get the css page and print it.

4
  • 2
    A CSS page from a website is just another resource you can retrieve by making an HTTP request (that's what your browser does). Just send an HTTP GET to the url your CSS is located at. Commented Aug 28, 2013 at 20:03
  • @Sotirios Delimanolis yeah but how do i get it if the given url and css location varies? Scanning for the link tag? Commented Aug 28, 2013 at 20:07
  • 1
    I don't understand what you mean. Are you scraping a page or do you know the exact url you want? Typically a css will be included with a link element that has a ref="stylesheet" attribute. stylesheet is not the content type, text/css is. Commented Aug 28, 2013 at 20:08
  • @Sotirios Delimanolis is some sort of crawler for intranet websites so yeah "scraping" Commented Aug 28, 2013 at 20:11

1 Answer 1

1

Take the code below for example

URL url = new URL("http://cdn.sstatic.net/stackoverflow/all.css?v=e97b23688ee8"); // some css on this site
HttpURLConnection con = (HttpURLConnection) url.openConnection();

Scanner scanner = new Scanner(con.getInputStream());
while(scanner.hasNextLine()) 
    System.out.println(scanner.nextLine());

System.out.println(con.getContentType()); // prints text/css

You were probably looking for the wrong Content-Type.

Sign up to request clarification or add additional context in comments.

8 Comments

Genious! that's what i needed thanks, now I just need a way to somehow detect and get the css link from html code BUT THAT'S ANOTHER HISTORY :D
@eon You're welcome. There are libraries to scan HTML pages and extract information. For example, jsoup.
@eon Step-by-step :) Also, consider accepting if the answer helped.
@eon Maybe this will be helpful. I don't know jsoup, but you can definitely extract the elements that have a ref="stylesheet" attribute.
thanks alot sir, welcome to my little list of awesome people. Heh!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.