tags:

views:

1826

answers:

3

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.

+1  A: 

Check out the URL and URLConnection classes. Here's some documentation: http://www.exampledepot.com/egs/java.net/Post.html

Moishe
Thanks for that, checking out now.
RodeoClown
+1  A: 

If the intention is to run another resource while your servlet is executing with out transferring control to the other resource you can try using include(request, response).

RequestDispatcher dispatcher =
   getServletContext().getRequestDispatcher("/url of other resource");
if (dispatcher != null)
   dispatcher.include(request, response);
}

You may put this on a servlet and the result of the other resource is included on your servlet.

EDIT: Since you are looking to get a file back then this solution works for that too.

Vincent Ramdhanie
Thanks Vincent.It doesn't look like that will quite meet what I am looking for - I'm not looking to include anything in the response. There is no response in this instance (it is a scheduled task that runs purely server-side).
RodeoClown
+5  A: 
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.

albertb
Hi Albert, thanks for that - I will try it out now.
RodeoClown