如何访问 url 并从 java servlet 获取响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12634213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access a url and get its response from java servlet?
提问by sindy90
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
我是 servlet 编程的新手,我的任务是编写一个 srvlet 程序,该程序将访问 url 并检索其内容。请帮助
采纳答案by Rahul Agrawal
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
纯java程序
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);
}
}
}
回答by MaVRoSCy
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.
这实际上是一个关于 Servlet 的基本问题。在 SO 中,我们有一些特殊的地方可以回答这些基本问题。只需单击servlet
右侧的标签,然后选择info
左上角的选项卡。或访问此链接https://stackoverflow.com/tags/servlets/info。
There is a basic example there on how you can use servlets.
那里有一个关于如何使用 servlet 的基本示例。