RVin
RVin

Reputation: 43

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

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!

Upvotes: 2

Views: 23615

Answers (3)

Dub Nazar
Dub Nazar

Reputation: 532

You can get a PrintWriter from HttpServletResponse.

Example:

resp.setContentType("text/plain");    // Not required
PrintWriter out = resp.getWriter();
out.write("POST something back to the GET Request");
out.flush();
out.close();    

Upvotes: 1

Ravindra Gullapalli
Ravindra Gullapalli

Reputation: 9178

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");
}

Upvotes: 4

tartak
tartak

Reputation: 485

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();
    }

Upvotes: 1

Related Questions