Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a file from an http request in java

Tags:

java

http

request

How do I call a url in order to process the results?

I have a stand-alone reporting servlet which I link to for reports. I want to email these reports now, if I were doing this in the browser, I could just use an xhttprequest, and process the results - I basically want to do the same thing in Java, but I'm not sure how to go about it.

UPDATE: I'm looking to get a file back from the url (whether that be a pdf or html etc).

UPDATE: This will be running purely on the server - there is no request that triggers the emailing, rather it is a scheduled email.

like image 274
RodeoClown Avatar asked Oct 27 '08 00:10

RodeoClown


1 Answers

public byte[] download(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    int len = uc.getContentLength();
    InputStream is = new BufferedInputStream(uc.getInputStream());
    try {
        byte[] data = new byte[len];
        int offset = 0;
        while (offset < len) {
            int read = is.read(data, offset, data.length - offset);
            if (read < 0) {
                break;
            }
          offset += read;
        }
        if (offset < len) {
            throw new IOException(
                String.format("Read %d bytes; expected %d", offset, len));
        }
        return data;
    } finally {
        is.close();
    }
}

Edit: Cleaned up the code.

like image 126
albertb Avatar answered Sep 28 '22 00:09

albertb