Java URL Connection getFeedReader(URL feedUrl)

Here you can find the source of getFeedReader(URL feedUrl)

Description

Creates a reader with the appropriate char encoding for the URL

License

Open Source License

Parameter

Parameter Description
feedUrl the Feed url

Exception

Parameter Description
IOException If an error occurs

Return

an appropriate reader

Declaration

public static Reader getFeedReader(URL feedUrl) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern CHARSET_PATTERN = Pattern.compile("charset=([.[^; ]]*)");

    /**/*  w ww .j  av a 2s .  com*/
     * Creates a reader with the appropriate char encoding for the URL
     * 
     * @param feedUrl the Feed url
     * @return an appropriate reader
     * @throws IOException If an error occurs
     */
    public static Reader getFeedReader(URL feedUrl) throws IOException {
        Reader reader;
        URLConnection conn = feedUrl.openConnection();

        if (feedUrl.getProtocol().equals("http") || feedUrl.getProtocol().equals("https")) {
            // Finds out server charset encoding based on HTTP spec
            String contentTypeHeader = conn.getContentType();
            String encoding = "ISO-8859-1";
            if (contentTypeHeader != null) {
                Matcher matcher = CHARSET_PATTERN.matcher(contentTypeHeader);
                if (matcher.find()) {
                    encoding = matcher.group(1);
                }
            }
            reader = new InputStreamReader(conn.getInputStream(), encoding);
        } else {
            // Goes with plartform's default charset encoding
            reader = new InputStreamReader(conn.getInputStream());
        }

        return reader;
    }
}

Related

  1. getConnectionResponseHeaders(URLConnection c)
  2. getContainerUrl(URL url, String resourceInThatDir)
  3. getCookies(URLConnection conn, Map> store)
  4. getDataFromServer(URL url)
  5. getDefaultUrlConnection(URL url)
  6. getFromUrl(String url)
  7. getGlobalAddress(String url)
  8. getGlobalIPAddress(URL automationPage)
  9. getHeaderFieldLong(URLConnection conn, String name, long Default)