|
Reading content from a URL in Java/JSP/Servlets
GOOD! a JSP programmer! Too many people dont do JSP. But the answer to your question is simple... You use java.net.URL object which has a OpenStream() method that returns an InputStream which you can use like a text file reading a line at a time and outputting to your own page.
<%@page import="java.io.*" %>
<%@page import="java.net.*" %>
<%
URL l_URL = new URL("http://www.google.com");
BufferedReader l_Reader = new BufferedReader( new InputStreamReader( l_URL.openStream()));
String l_InputLine = null ;
while ((l_InputLine = l_Reader.readLine()) != null)
out.println( l_InputLine );
l_Reader.close();
%>
This code is very useful for 'borrowing' content from another site in server-side processing so that you get the content of the other site but not show any links to it. Furthermore, you can parse the content and pull only what you want. And if you have a firewall at work that restricts you from viewing certain sites or you want to view, you can use this to get the content of that site provided this code is ran from a trusted server that is allowed by your firewall.
Once you have the above code working, you can bring it to the next level and maybe have a form that takes a url as input and get the content. Save the code below as: geturlcontent.jsp
<%@page import="java.io.*" %>
<%@page import="java.net.*" %>
<%
String a_Url = request.getParameter( "url" ) ;
String l_Content = "" ;
if( a_Url!=null && a_Url.length()>0 )
l_Content = GetContent( a_Url ).toString() ;
%>
<%!
StringBuffer GetContent( String a_Url ) throws Exception
{
URL l_URL = new URL(a_Url);
BufferedReader l_Reader = new BufferedReader( new InputStreamReader( l_URL.openStream()));
StringBuffer l_Result = new StringBuffer("") ;
String l_InputLine = null ;
while ((l_InputLine = l_Reader.readLine()) != null)
l_Result.append( l_InputLine );
l_Reader.close();
return( l_Result ) ;
}
%>
<form method="get" action="geturlcontent.jsp">
URL : <input type=text" name="url" value="http://www.google.com"><br>
<input type="submit">
</form>
<hr>
<%=l_Content%>
|