Spring 406 error

declaration: package: org.springframework.http, enum: HttpStatus

Enum Constant Details

  • CONTINUE

    100 Continue.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.2.1
  • SWITCHING_PROTOCOLS

    public static final HttpStatus SWITCHING_PROTOCOLS

    101 Switching Protocols.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.2.2
  • PROCESSING

    public static final HttpStatus PROCESSING

    102 Processing.

    See Also:
    • WebDAV
  • CHECKPOINT

    public static final HttpStatus CHECKPOINT

    103 Checkpoint.

    See Also:
    • A proposal for supporting
      resumable POST/PUT HTTP requests in HTTP/1.0
  • OK

    200 OK.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.3.1
  • CREATED

    201 Created.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.3.2
  • ACCEPTED

    202 Accepted.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.3.3
  • NON_AUTHORITATIVE_INFORMATION

    public static final HttpStatus NON_AUTHORITATIVE_INFORMATION

    203 Non-Authoritative Information.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.3.4
  • NO_CONTENT

    public static final HttpStatus NO_CONTENT

    204 No Content.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.3.5
  • RESET_CONTENT

    public static final HttpStatus RESET_CONTENT

    205 Reset Content.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.3.6
  • PARTIAL_CONTENT

    public static final HttpStatus PARTIAL_CONTENT

    206 Partial Content.

    See Also:
    • HTTP/1.1: Range Requests, section 4.1
  • MULTI_STATUS

    public static final HttpStatus MULTI_STATUS

    207 Multi-Status.

    See Also:
    • WebDAV
  • ALREADY_REPORTED

    public static final HttpStatus ALREADY_REPORTED

    208 Already Reported.

    See Also:
    • WebDAV Binding Extensions
  • IM_USED

    226 IM Used.

    See Also:
    • Delta encoding in HTTP
  • MULTIPLE_CHOICES

    public static final HttpStatus MULTIPLE_CHOICES

    300 Multiple Choices.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.4.1
  • MOVED_PERMANENTLY

    public static final HttpStatus MOVED_PERMANENTLY

    301 Moved Permanently.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.4.2
  • FOUND

    302 Found.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.4.3
  • MOVED_TEMPORARILY

    302 Moved Temporarily.

    See Also:
    • HTTP/1.0, section 9.3
  • SEE_OTHER

    303 See Other.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.4.4
  • NOT_MODIFIED

    public static final HttpStatus NOT_MODIFIED

    304 Not Modified.

    See Also:
    • HTTP/1.1: Conditional Requests, section 4.1
  • USE_PROXY

    305 Use Proxy.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.4.5
  • TEMPORARY_REDIRECT

    public static final HttpStatus TEMPORARY_REDIRECT

    307 Temporary Redirect.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.4.7
  • PERMANENT_REDIRECT

    public static final HttpStatus PERMANENT_REDIRECT

    308 Permanent Redirect.

    See Also:
    • RFC 7238
  • BAD_REQUEST

    public static final HttpStatus BAD_REQUEST

    400 Bad Request.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.1
  • UNAUTHORIZED

    public static final HttpStatus UNAUTHORIZED

    401 Unauthorized.

    See Also:
    • HTTP/1.1: Authentication, section 3.1
  • PAYMENT_REQUIRED

    public static final HttpStatus PAYMENT_REQUIRED

    402 Payment Required.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.2
  • FORBIDDEN

    403 Forbidden.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.3
  • NOT_FOUND

    404 Not Found.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.4
  • METHOD_NOT_ALLOWED

    public static final HttpStatus METHOD_NOT_ALLOWED

    405 Method Not Allowed.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.5
  • NOT_ACCEPTABLE

    public static final HttpStatus NOT_ACCEPTABLE

    406 Not Acceptable.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.6
  • PROXY_AUTHENTICATION_REQUIRED

    public static final HttpStatus PROXY_AUTHENTICATION_REQUIRED

    407 Proxy Authentication Required.

    See Also:
    • HTTP/1.1: Authentication, section 3.2
  • REQUEST_TIMEOUT

    public static final HttpStatus REQUEST_TIMEOUT

    408 Request Timeout.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.7
  • CONFLICT

    409 Conflict.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.8
  • GONE

    410 Gone.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.9
  • LENGTH_REQUIRED

    public static final HttpStatus LENGTH_REQUIRED

    411 Length Required.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.10
  • PRECONDITION_FAILED

    public static final HttpStatus PRECONDITION_FAILED

    412 Precondition failed.

    See Also:
    • HTTP/1.1: Conditional Requests, section 4.2
  • PAYLOAD_TOO_LARGE

    public static final HttpStatus PAYLOAD_TOO_LARGE

    413 Payload Too Large.

    Since:
    4.1
    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.11
  • REQUEST_ENTITY_TOO_LARGE

    413 Request Entity Too Large.

    See Also:
    • HTTP/1.1, section 10.4.14
  • URI_TOO_LONG

    public static final HttpStatus URI_TOO_LONG

    414 URI Too Long.

    Since:
    4.1
    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.12
  • REQUEST_URI_TOO_LONG

    414 Request-URI Too Long.

    See Also:
    • HTTP/1.1, section 10.4.15
  • UNSUPPORTED_MEDIA_TYPE

    public static final HttpStatus UNSUPPORTED_MEDIA_TYPE

    415 Unsupported Media Type.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.13
  • REQUESTED_RANGE_NOT_SATISFIABLE

    public static final HttpStatus REQUESTED_RANGE_NOT_SATISFIABLE

    416 Requested Range Not Satisfiable.

    See Also:
    • HTTP/1.1: Range Requests, section 4.4
  • EXPECTATION_FAILED

    public static final HttpStatus EXPECTATION_FAILED

    417 Expectation Failed.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.5.14
  • I_AM_A_TEAPOT

    public static final HttpStatus I_AM_A_TEAPOT

    418 I'm a teapot.

    See Also:
    • HTCPCP/1.0
  • INSUFFICIENT_SPACE_ON_RESOURCE

  • METHOD_FAILURE

  • DESTINATION_LOCKED

  • UNPROCESSABLE_ENTITY

    public static final HttpStatus UNPROCESSABLE_ENTITY

    422 Unprocessable Entity.

    See Also:
    • WebDAV
  • LOCKED

    423 Locked.

    See Also:
    • WebDAV
  • FAILED_DEPENDENCY

    public static final HttpStatus FAILED_DEPENDENCY

    424 Failed Dependency.

    See Also:
    • WebDAV
  • TOO_EARLY

    425 Too Early.

    Since:
    5.2
    See Also:
    • RFC 8470
  • UPGRADE_REQUIRED

    public static final HttpStatus UPGRADE_REQUIRED

    426 Upgrade Required.

    See Also:
    • Upgrading to TLS Within HTTP/1.1
  • PRECONDITION_REQUIRED

    public static final HttpStatus PRECONDITION_REQUIRED

    428 Precondition Required.

    See Also:
    • Additional HTTP Status Codes
  • TOO_MANY_REQUESTS

    public static final HttpStatus TOO_MANY_REQUESTS

    429 Too Many Requests.

    See Also:
    • Additional HTTP Status Codes
  • UNAVAILABLE_FOR_LEGAL_REASONS

    public static final HttpStatus UNAVAILABLE_FOR_LEGAL_REASONS

    451 Unavailable For Legal Reasons.

    Since:
    4.3
    See Also:
    • An HTTP Status Code to Report Legal Obstacles
  • INTERNAL_SERVER_ERROR

    public static final HttpStatus INTERNAL_SERVER_ERROR

    500 Internal Server Error.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.6.1
  • NOT_IMPLEMENTED

    public static final HttpStatus NOT_IMPLEMENTED

    501 Not Implemented.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.6.2
  • BAD_GATEWAY

    public static final HttpStatus BAD_GATEWAY

    502 Bad Gateway.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.6.3
  • SERVICE_UNAVAILABLE

    public static final HttpStatus SERVICE_UNAVAILABLE

    503 Service Unavailable.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.6.4
  • GATEWAY_TIMEOUT

    public static final HttpStatus GATEWAY_TIMEOUT

    504 Gateway Timeout.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.6.5
  • HTTP_VERSION_NOT_SUPPORTED

    public static final HttpStatus HTTP_VERSION_NOT_SUPPORTED

    505 HTTP Version Not Supported.

    See Also:
    • HTTP/1.1: Semantics and Content, section 6.6.6
  • VARIANT_ALSO_NEGOTIATES

    public static final HttpStatus VARIANT_ALSO_NEGOTIATES

    506 Variant Also Negotiates

    See Also:
    • Transparent Content Negotiation
  • INSUFFICIENT_STORAGE

    public static final HttpStatus INSUFFICIENT_STORAGE

    507 Insufficient Storage

    See Also:
    • WebDAV
  • LOOP_DETECTED

    public static final HttpStatus LOOP_DETECTED

    508 Loop Detected

    See Also:
    • WebDAV Binding Extensions
  • BANDWIDTH_LIMIT_EXCEEDED

    public static final HttpStatus BANDWIDTH_LIMIT_EXCEEDED

    509 Bandwidth Limit Exceeded

  • NOT_EXTENDED

    public static final HttpStatus NOT_EXTENDED

    510 Not Extended

    See Also:
    • HTTP Extension Framework
  • NETWORK_AUTHENTICATION_REQUIRED

    public static final HttpStatus NETWORK_AUTHENTICATION_REQUIRED

    511 Network Authentication Required.

    See Also:
    • Additional HTTP Status Codes

Method Details

  • values

    Returns an array containing the constants of this enum class, in
    the order they are declared.

    Returns:
    an array containing the constants of this enum class, in the order they are declared
  • valueOf

    Returns the enum constant of this class with the specified name.
    The string must match exactly an identifier used to declare an
    enum constant in this class. (Extraneous whitespace characters are
    not permitted.)

    Parameters:
    name — the name of the enum constant to be returned.
    Returns:
    the enum constant with the specified name
    Throws:
    IllegalArgumentException — if this enum class has no constant with the specified name
    NullPointerException — if the argument is null
  • value

    public int value()

    Return the integer value of this status code.

    Specified by:
    value in interface HttpStatusCode
  • series

    Return the HTTP status series of this status code.

    See Also:
    • HttpStatus.Series
  • getReasonPhrase

    public String getReasonPhrase()

    Return the reason phrase of this status code.

  • is1xxInformational

    public boolean is1xxInformational()

    Whether this status code is in the Informational class (1xx).

    Specified by:
    is1xxInformational in interface HttpStatusCode
    See Also:
    • RFC 2616
  • is2xxSuccessful

    public boolean is2xxSuccessful()

    Whether this status code is in the Successful class (2xx).

    Specified by:
    is2xxSuccessful in interface HttpStatusCode
    See Also:
    • RFC 2616
  • is3xxRedirection

    public boolean is3xxRedirection()

    Whether this status code is in the Redirection class (3xx).

    Specified by:
    is3xxRedirection in interface HttpStatusCode
    See Also:
    • RFC 2616
  • is4xxClientError

    public boolean is4xxClientError()

    Whether this status code is in the Client Error class (4xx).

    Specified by:
    is4xxClientError in interface HttpStatusCode
    See Also:
    • RFC 2616
  • is5xxServerError

    public boolean is5xxServerError()

    Whether this status code is in the Server Error class (5xx).

    Specified by:
    is5xxServerError in interface HttpStatusCode
    See Also:
    • RFC 2616
  • isError

    public boolean isError()

    Whether this status code is in the Client or Server Error class

    Specified by:
    isError in interface HttpStatusCode
    See Also:
    • RFC 2616
    • RFC 2616
      (4xx or 5xx).
    • HttpStatusCode.is4xxClientError()
    • HttpStatusCode.is5xxServerError()
  • toString

    Return a string representation of this status code.

    Overrides:
    toString in class Enum<HttpStatus>
  • valueOf

    public static HttpStatus valueOf(int statusCode)

    Return the HttpStatus enum constant with the specified numeric value.

    Parameters:
    statusCode — the numeric value of the enum to be returned
    Returns:
    the enum constant with the specified numeric value
    Throws:
    IllegalArgumentException — if this enum has no constant for the specified numeric value
  • resolve

    Resolve the given status code to an HttpStatus, if possible.

    Parameters:
    statusCode — the HTTP status code (potentially non-standard)
    Returns:
    the corresponding HttpStatus, or null if not found
    Since:
    5.0

Spring MVC + JSON = 406 Not Acceptable + characteristics not acceptable according to the request “accept” headers ()


Posted on December 1, 2015 Updated on January 3, 2018

This is the  very common mistake that typically happened during the configuration Spring + JSON. Recently we faced such issues with Spring 4 + Hibernate configuration so by digging some blogs and own effort make this issues fixed.

below are some steps that need to be changed in configuration file so we can get rid of “Response Error 406 :-characteristics not acceptable according to the request “accept” headers ()

Get rid of this issues by adding **@EnableWebMvc** in Controller class.

@Controller
@RequestMapping("/API/course")
@EnableWebMvc
public class CourseController {
@Autowired
private com.item.DAO.CourseRepository courseRepository;

@ResponseStatus(value=HttpStatus.OK)
@RequestMapping(method=RequestMethod.GET)
public @ResponseBody List&lt;Course&gt; getListOfCourse(){
List&lt;Course&gt; courses = courseRepository.getListOfCourse();
return courses ;
}

or add following lines in xml configuration file if XML configuration is being used in your project.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<bean>

and add following dependencies in your pom.xml file:-

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.1</version>
</dependency>

See complate example here.

We hope this will help you out, Thanks !!

This entry was posted in Spring and tagged Spring.

 

Jackson-core-asl-1.9.12.jar Jackson-mapper-asl-1.9.12.jar
The test is not for this error and does not have to rely on the two JARs.
The following configuration returns data normally

 
pom.xml

        <!-- Jackson JSON Processor -->

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
 

 
For springMvc. In the XML

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="false">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=utf-8</value>
                        <value>text/xml;charset=utf-8</value>
                        <value>text/plain;</value>
                        <value>text/json;charset=utf-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

 
 
 
 
In the Controller

  @RequestMapping(value = "checkLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto checkLogin(String name, String password, int role) {

        return loginService.checkLogin(name, password, role);
    }
 

 
 
——————————————————————————-
The ResultDTO object is missing some of the GET methods, causing an error in formatting the JSON object.
Remove the above two JARs and test with the GET method of the returned object, reporting 406 error code.
The debug code in ServletInvocableHandlerMethod. Catch exceptions in the class “Could not find acceptable representation.” ”
After adding the get method, the test returns the JSON character of the object normally

public class ResultDto {

    private boolean succeed;
    private Object data;

    public ResultDto(boolean succeed) {
        this.succeed = succeed;
    }

    public ResultDto(boolean succeed, Object data) {
        this.succeed = succeed;
        this.data = data;
    }

/*
    public boolean isSucceed() {
        return succeed;
    }

    public Object getData() {
        return data;
    }
*/

    public void setSucceed(boolean succeed) {
        this.succeed = succeed;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

Read More:

I’m using Spring Webflux and seeing 406 errors when both of the following occur:

  1. Exceptions are returned from the the Reactive stream instead of the controller method itself.
  2. When the controller method produces a different ContentType then the ExceptionHandler.

This is reproducible using SpringBoot v2.0.3 and v2.1.0-BUILD-SNAPSHOT (as of today).

@RestController
@RequiredArgsConstructor
class BinaryTestController {

  private final AccessKeyValidationService accessKeyValidationService;

  @GetMapping(path = "/binary-test", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  Mono<byte[]> test(@RequestParam("apiKey") String apiKey, @RequestParam(name = "failFirst", required = false) boolean failFirst) {

    if (failFirst) { throw new IllegalArgumentException();}

    return Mono.just(apiKey)
        .filterWhen(accessKeyValidationService::isValid)
        .switchIfEmpty(Mono.error(new IllegalAccessException()))
        .then(Mono.just("test".getBytes(StandardCharsets.UTF_8)));
  }

  @ExceptionHandler(IllegalArgumentException.class)
  ResponseEntity<Mono<BadResponse>> handleIllegalArgumentException() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    return new ResponseEntity<>(Mono.just(new BadResponse("better luck next time")), headers, HttpStatus.BAD_REQUEST);
  }

  @ExceptionHandler(IllegalAccessException.class)
  ResponseEntity<Mono<BadResponse>> handleIllegalAccessException() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    return new ResponseEntity<>(Mono.just(new BadResponse("access denied")), headers, HttpStatus.FORBIDDEN);
  }

  @Data
  class BadResponse {
    private final String developerMessage;
  }

}

The AccessKeyValidationService does a blocking lookup, so naturally needs to return a Mono and thus needs to be part of the Mono returned from the controller:

@Service
class AccessKeyValidationService {

  Mono<Boolean> isValid(String accessKey) {
    return Mono.defer(() -> Mono.just(blockingLookup(accessKey)))
        .subscribeOn(Schedulers.elastic());
  }

  private Boolean blockingLookup(String accessKey) {
    //Some blocking lookup...
    return accessKey.equals("good");
  }
}

A valid apiKey, results in proper binary output:

$ http localhost:8080/binary-test apiKey==good
HTTP/1.1 200 OK
Content-Length: 4
Content-Type: application/octet-stream

test

When I throw an exception before the Reactive Stream, I get the intended JSON output:

$ http localhost:8080/binary-test apiKey==good failFirst==true
HTTP/1.1 400 Bad Request
Content-Length: 44
Content-Type: application/json;charset=UTF-8

{
    "developerMessage": "better luck next time"
}

But when I trigger the steam to error with an IllegalAccessException, I get a 406:

$ http localhost:8080/binary-test apiKey==bad
HTTP/1.1 406 Not Acceptable
Content-Length: 157
Content-Type: application/json;charset=UTF-8

{
    "error": "Not Acceptable",
    "message": "Could not find acceptable representation",
    "path": "/binary-test",
    "status": 406,
    "timestamp": "2018-06-30T05:23:09.820+0000"
}

If I put a breakpoint in the handleIllegalAccessException method, it stops as expected.

If I switch the return type for the controller method to JSON it works as expected.

Is there something else I need to do to switch the response type when erroring out the returned Mono? Or some other way to resolve it?

Here’s a repo with a failing unit test reproducing the problem: https://github.com/pluttrell/spring-webflux-binary-response-exception-handling-example

Понравилась статья? Поделить с друзьями:
  • Spotify как изменить адрес электронной почты
  • Spotify installer error code 24 как исправить
  • Spore как изменить цвет империи на этапе космос
  • Spore как изменить существо на этапе космос
  • Spooler subsystem app обнаружена ошибка приложение будет закрыто windows xp