5

I am new to servlet programming my task is to write a srvlet program that will access a url and retrieve its contents .pls do help

1
  • You should be able to take advantage of the java.net.URL and it's associated java.net.URLConnection to read the contents. You might like to provide some more details about what it is you're trying to do, as I'm not entirely sure this will meet your needs Commented Sep 28, 2012 at 5:48

2 Answers 2

4

You need to do something like this

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.*;
import javax.servlet.*;


public class URLServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        URL urldemo = new URL("http://www.demo.com/");
        URLConnection yc = urldemo.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();

    }
}

Plain java Program

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLServlet {

    public static void main(String s[]) {
        try {
        URL urldemo = new URL("http://www.google.com/");
        URLConnection yc = urldemo.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        }catch(Exception e) {
            System.out.println(e);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Rahul i tried ur code but each time i try to connect i get a connection refused error ! i tried connecting to www.google.com
It is working at my end. I have tried using simple java program, code attached above
2

This is actually a basic question regarding Servlets. In SO we have special places that such basic questions are answered. Just click the servlet tag on your right and then select the info tab in your top left. Or visit this link https://stackoverflow.com/tags/servlets/info .

There is a basic example there on how you can use servlets.

Comments

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.