Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31215

Custom HTTP status code

I consider using fluent-http in a project.

I started with a simple "login/password" page. I create a simple POJO with fields login and password :

public class LoginRequest() {
  private String login;
  private String password;
  //...
}

And I send it to fluent-http via a Resource :

@Prefix("/user")
public class PersonResource {

  @Post("/")
  public String get(LoginRequest loginRequest) {
    //[...]
  }
}

And it works well :)

Now, I wondered if it was possible to send a response with code HTTP 200 in case of success and code HTTP 401 in case of failure.

So I tried to inject the Response :

@Post("/")
public String login(LoginRequest loginRequest, Response response) {
  if(loginRequest.getPassword().equals("helloworld")) {
    response.setStatus(200);
    return "SUCCESS";
  } else {
    response.setStatus(401);
    return "ERROR";
  }
}

The correct String is returned but the status code does not seem to be used. In both cases, the response has a code HTTP 200.

Note : I found that some status code are pre-implemented :

Any idea?

Upvotes: 4

Views: 2050

Answers (1)

David Gageot
David Gageot

Reputation: 2536

If you want to change the default content-type, status or headers, the method should return a net.codestory.http.payload.Payload.

Here's what you should write:

@Post("/")
public Payload login(LoginRequest loginRequest) {
  if(!loginRequest.getPassword().equals("helloworld")) {
    return new Payload("ERROR").withCode(HttpStatus.UNAUTHORIZED);
  }

  return new Payload("SUCCESS").withCode(HttpStatus.CREATED);
}

Upvotes: 1

Related Questions