How to access a url and get its response from a Java servlet?

I am new to servlet programming. My task is to write a srvlet program that will access the URL and get its contents .pls help

+4
source share
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(); } } 

Simple 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); } } } 
+4
source

This is actually the main question about servlets. At SO, we have special places that answer such basic questions. Just click the servlet tag on the right, and then select the info tab in the upper left corner. Or visit this link fooobar.com/tags/servlets / ....

There is a basic example of how you can use servlets.

+2
source

Source: https://habr.com/ru/post/1436746/


All Articles