I'm learning about servlets in java and I'm trying to capture a URL content and store it into a string array. Bellow is my code that I put together following some tutorials that does not seem to work servlet environment (This is the first part of an exercise that I'm trying to do).
I'm getting the error at this line:
cookies.add(line);
Here is the complete code:
//package fortune;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static java.util.Arrays.*;
@WebServlet(name = "FortuneServlet", urlPatterns = {"/"})
public class FortuneServlet extends HttpServlet {
private String [] cookies = null;
//ArrayList<String[]> cookies = new ArrayList<String[]>();
public void geturl(String[] args) {
try
{
URL url = new URL(" http://fortunes.cat-v.org/openbsd/");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = in.readLine();
while((line = in.readLine()) != null)
{
cookies.add(line);
line = in.readLine();
}
in.close();
}
catch (java.net.MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
public void init() throws ServletException {
// Add your own code here!
// 1) Open the URL
// 2) Get the contents
// 3) Extract the cookie texts to an array
}
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
if (cookies != null) {
response.getWriter().println(
cookies[new Random().nextInt(cookies.length)]
);
} else {
response.getWriter().println("No luck!");
}
}
}