Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 2nd, 2012  |  syntax: None  |  size: 1.85 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to send a HTTP Response to a HTTP Request in a Live Thread
  2. public void handle(String target, HttpServletRequest request,
  3.                    HttpServletResponse response, int dispatch)
  4.        throws IOException {
  5.   // Scan request into a string
  6.   Scanner scanner = new Scanner(request.getInputStream());
  7.   StringBuilder sb = new StringBuilder();
  8.   while (scanner.hasNextLine()) {
  9.     sb.append(scanner.nextLine());
  10.   }
  11.        
  12. GET / HTTP/1.1
  13. Host: 10.10.10.100:8800
  14. User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0) Gecko/20100101 Firefox/10.0
  15. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  16. Accept-Language: en-us,en;q=0.5
  17. Accept-Encoding: gzip, deflate
  18. Connection: keep-alive
  19.        
  20. HTTP/1.1 200
  21.        
  22. POST something back to the GET Request
  23.        
  24. public void handle(String target, HttpServletRequest request,
  25.                    HttpServletResponse response, int dispatch)
  26.        throws IOException {
  27.   // Scan request into a string
  28.   Scanner scanner = new Scanner(request.getInputStream());
  29.   StringBuilder sb = new StringBuilder();
  30.   while (scanner.hasNextLine()) {
  31.     sb.append(scanner.nextLine());
  32.   }
  33.   response.getOutputStream().println("This is servlet response");
  34. }
  35.        
  36. public void doPost(HttpServletRequest request,
  37.             HttpServletResponse response) throws ServletException,
  38.             IOException {
  39.  
  40.         DataInputStream in =
  41.                 new DataInputStream((InputStream)request.getInputStream());
  42.  
  43.         String text = in.readUTF();
  44.         String message;
  45.         try {
  46.             message = "100 ok";
  47.         } catch (Throwable t) {
  48.             message = "200 " + t.toString();
  49.         }
  50.         response.setContentType("text/plain");
  51.         response.setContentLength(message.length());
  52.         PrintWriter out = response.getWriter();
  53.         out.println(message);
  54.         in.close();
  55.         out.close();
  56.         out.flush();
  57.     }