Monday, September 29, 2008

Java HTTP Get without HTTPClient

Simple Java code for an HTTP GET (without needing HTTP client). Basic stuff, but thought I'd be the umpteenth person to log it:
import java.net.URL;
import java.net.MalformedURLException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory
...

    private Log log = LogFactory.getLog(this.getClass());

    ...

    private String doGet(String url) {
        StringBuffer sb = new StringBuffer();
        BufferedReader in = null;
        try {
            URL urlObj = new URL(url);
            in = new BufferedReader(new InputStreamReader(urlObj.openStream()));
            String s;
            while ((s = in.readLine()) != null) {
                sb.append(s);
                sb.append("\n");
            }            
        }
        catch (MalformedURLException mue) {
            log.warn("Bad url: '" + url + "'", mue);
        }
        catch (IOException ioe) {
            log.warn("Problem getting data at url: '" + url + "'", ioe);
        }
        finally {
            if (in!=null) {
                try {
                    in.close();
                }
                catch (Throwable t) {
                    log.warn("Failed to close stream to url: '" + url + "'", t);
                }
            }
        }
        
        return sb.toString();
    }

    ...

No comments: