Seawind Shi
Seawind Shi

Reputation: 143

Java servlet send send back response

I am trying to send some text back from server side to the client. I have tried response.setStatus, response.setHeader but they all does not work. I need some help

Here is my client:

 public static void main(String[] args) throws MalformedURLException, IOException {
    URL url = new URL("http://localhost:8080/WebServiceDesignStyles3ProjectServer/NewServlet/www");

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Accept", "text/xml");
    con.setDoOutput(true);
    con.setDoInput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeUTF("aaa");
    wr.flush();
    wr.close();

    InputStream is = con.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuffer response = new StringBuffer();
    while ((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    rd.close();
    System.out.println(response);
    System.out.println(con.getResponseCode());
    System.out.println(con.getResponseMessage());

}

}

Here is my doGET method from server:

   @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
 response.setStatus(404);
  response.setContentType("text/xml");
  PrintWriter writer=response.getWriter();
  writer.append("this is 404");
 writer.flush();






}

But my client still prints out 200 and OK, which are default. How can I send some message back to client.

Edit:

Solved, I should not have request body for doGet.

Thanks.

Upvotes: 0

Views: 13068

Answers (2)

user207421
user207421

Reputation: 310840

When you set doOutput to true you also set the request method to POST: see the Javadoc. So your doGet() method isn't being invoked.

It doesn't make sense to try to combine GET with output to the request. A GET request cannot have a request body.

Upvotes: 3

Scruffy
Scruffy

Reputation: 580

Actually doPost is invoked.

That presumably doesn't have the lines

response.setStatus(404);
response.setContentType("text/xml");
PrintWriter writer=response.getWriter();
writer.append("this is 404");

Either ensure doGet() is being used or implement the above in doPost().

Upvotes: 3

Related Questions