简体   繁体   中英

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

我是servlet编程的新手,我的任务是编写一个srvlet程序,该程序将访问url并检索其内容。

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);
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM