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
2 Answers
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);
}
}
}
2 Comments
sindy90
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
Rahul Agrawal
It is working at my end. I have tried using simple java program, code attached above
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.
java.net.URLand it's associatedjava.net.URLConnectionto 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