How to send a HTTP Response to a HTTP Request in a Live Thread

20,508

Solution 1

Add the response post at the end of handle method like this

public void handle(String target, HttpServletRequest request,
                   HttpServletResponse response, int dispatch)
       throws IOException {
  // Scan request into a string
  Scanner scanner = new Scanner(request.getInputStream());
  StringBuilder sb = new StringBuilder();
  while (scanner.hasNextLine()) {
    sb.append(scanner.nextLine());
  }
  response.getOutputStream().println("This is servlet response");
}

Solution 2

Well, let's say you override the doPost method.

public void doPost(HttpServletRequest request, 
            HttpServletResponse response) throws ServletException, 
            IOException {

        DataInputStream in = 
                new DataInputStream((InputStream)request.getInputStream());

        String text = in.readUTF();
        String message;
        try {
            message = "100 ok";
        } catch (Throwable t) {
            message = "200 " + t.toString();
        }
        response.setContentType("text/plain");
        response.setContentLength(message.length());
        PrintWriter out = response.getWriter();
        out.println(message);
        in.close();
        out.close();
        out.flush();
    }
Share:
20,508
RVin
Author by

RVin

Updated on October 25, 2020

Comments

  • RVin
    RVin over 3 years

    I'm new to Java and I'm getting the HttpServletRequest, but I have no clue how to respond to the request using the HttpServletResponse.

    Here is my example code:

    public void handle(String target, HttpServletRequest request,
                       HttpServletResponse response, int dispatch)
           throws IOException {
      // Scan request into a string
      Scanner scanner = new Scanner(request.getInputStream());
      StringBuilder sb = new StringBuilder();
      while (scanner.hasNextLine()) {
        sb.append(scanner.nextLine());
      }
    

    This is the sample request I'm getting:

    GET / HTTP/1.1
    Host: 10.10.10.100:8800
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0) Gecko/20100101 Firefox/10.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-us,en;q=0.5
    Accept-Encoding: gzip, deflate
    Connection: keep-alive
    

    By default the response is

    
    HTTP/1.1 200 
    But I want the rosponse something like
    POST something back to the GET Request
    how can I do it. and where am I suppose to add the code...?? I'm actually pretty lost in this whole thing and rather uncomfortable with Java still, so I have no idea what I'm missing. Any pointers are greatly appreciated. Thanks!