Java org.springframework.http.converter.HttpMessageNotReadableException 代码实例

・13 分钟阅读

以下是展示如何使用org.springframework.http.converter.HttpMessageNotReadableException的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Override
protected URI readInternal(Class<? extends URI> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    InputStream in = null;
    try {
        in = inputMessage.getBody();
        String uri = IOUtils.toString(in);
        if (inputMessage.getHeaders().getContentType() == MediaType.APPLICATION_FORM_URLENCODED) {
            uri = URLDecoder.decode(uri, "UTF-8");
        }
        return new URI(uri);
    } catch (URISyntaxException urie) {
        throw new HttpMessageNotReadableException("Failed to parse incoming String into a URI.", urie);
    } finally {
        IOUtils.closeQuietly(in);
    }
}
 

实例 2


@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
    throws IOException, HttpMessageNotReadableException {
  JavaType javaType = getJavaType(clazz);
  try {
    return success(clazz, inputMessage);
    // return this.objectMapper.readValue(inputMessage.getBody(),
    // javaType);
  } catch (Exception ex) {
    throw new HttpMessageNotReadableException("Could not read JSON: "
        + ex.getMessage(), ex);
  }
}
 

实例 3


@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException {
        try (Reader reader = new InputStreamReader(inputMessage.getBody(), StandardCharsets.UTF_8)) {
                return gson.fromJson(reader, clazz);
        } catch (JsonSyntaxException e) {
                throw new HttpMessageNotReadableException("Could not read JSON: " + e.getMessage(), e);
        }
}
 

实例 4


@Test
public void shouldThrowOnFailedConversionBecauseOfFaultyBody() {
    server.expect(requestTo(url))
            .andRespond(withSuccess()
                    .body("{")
                    .contentType(MediaTypes.SUCCESS));
    exception.expect(HttpMessageNotReadableException.class);
    exception.expectMessage("Could not read JSON");
    unit.execute(GET, url)
            .dispatch(status(),
                    on(HttpStatus.OK)
                            .dispatch(series(),
                                    on(SUCCESSFUL, Success.class).capture(),
                                    anySeries().capture()),
                    on(HttpStatus.CREATED, Success.class).capture(),
                    anyStatus().call(this::fail));
}
 

实例 5


@ExceptionHandler({HttpMessageNotReadableException.class})
public ResponseEntity<Object> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) {
    logger.error("Request not readable: {}", exception.toString());
    StatusCode statusCode = new StatusCode();
    statusCode.setCode("400");
    statusCode.setReasonPhrase(exception.getMessage());
    if (exception.getCause() != null) {
        statusCode.setDetail(exception.getCause().getMessage());
    }
    return new ResponseEntity<>(statusCode, HttpStatus.BAD_REQUEST);
}
 

实例 6


@SuppressWarnings( "static-access" )
@Test
public void testReadInternal() throws HttpMessageNotReadableException, IOException
{
    Assert.assertNotNull( jaxbHelper );
    List< Object > list = new ArrayList< Object >();
    list.add( new SettopDesc() );
    InputStream inputStream = EasyMock.createMock( InputStream.class );
    HttpInputMessage inputMessage = EasyMock.createMock( HttpInputMessage.class );
    expect( inputMessage.getBody() ).andReturn( inputStream );
    EasyMock.replay( inputStream, inputMessage );
    PowerMock.mockStatic( JAXBHelper.class );
    EasyMock.expect( jaxbHelper.readExternalList( inputStream, SettopDesc.class ) ).andReturn( list );
    PowerMock.replayAll();
    @SuppressWarnings( "unchecked" )
    List< Object > result = ( List< Object > ) jaxbListHttpMessageConverter.readInternal( SettopDesc.class,
            inputMessage );
    EasyMock.verify( inputMessage );
    PowerMock.verifyAll();
    Assert.assertNotNull( result );
}
 

实例 7


@RequestMapping("/sparklr/photos/{id}")
public ResponseEntity<BufferedImage> photo(@PathVariable String id) throws Exception {
        InputStream photo = sparklrService.loadSparklrPhoto(id);
        if (photo == null) {
                throw new UnavailableException("The requested photo does not exist");
        }
        BufferedImage body;
        MediaType contentType = MediaType.IMAGE_JPEG;
        Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
        if (imageReaders.hasNext()) {
                ImageReader imageReader = imageReaders.next();
                ImageReadParam irp = imageReader.getDefaultReadParam();
                imageReader.setInput(new MemoryCacheImageInputStream(photo), true);
                body = imageReader.read(0, irp);
        } else {
                throw new HttpMessageNotReadableException("Could not find javax.imageio.ImageReader for Content-Type ["
                                + contentType + "]");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<BufferedImage>(body, headers, HttpStatus.OK);
}
 

实例 8


@Override
protected ExceptionReport readInternal(Class<? extends ExceptionReport> clazz, HttpInputMessage inputMessage)
                throws IOException, HttpMessageNotReadableException {
    for (HttpMessageConverter<?> converter : messageConverters) {
        for (MediaType mediaType : converter.getSupportedMediaTypes()) {
            if (converter.canRead(Map.class, mediaType)) {
                @SuppressWarnings({ "rawtypes", "unchecked" })
                HttpMessageConverter<Map> messageConverter = (HttpMessageConverter<Map>) converter;
                @SuppressWarnings("unchecked")
                Map<String, String> map = messageConverter.read(Map.class, inputMessage);
                return new ExceptionReport(getException(map));
            }
        }
    }
    return null;
}
 

实例 9


@Override
protected Message readInternal(Class<? extends Message> clazz, HttpInputMessage inputMessage)
                throws IOException, HttpMessageNotReadableException {
       MediaType contentType = inputMessage.getHeaders().getContentType();
        contentType = (contentType != null ? contentType : PROTOBUF);
        Charset charset = getCharset(inputMessage.getHeaders());
        InputStreamReader reader = new InputStreamReader(inputMessage.getBody(), charset);
        try {
                Message.Builder builder = getMessageBuilder(clazz);
                if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
                        JsonFormat.merge(reader, this.extensionRegistry, builder);
                }
                else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) {
                        TextFormat.merge(reader, this.extensionRegistry, builder);
                }
                else if (MediaType.APPLICATION_XML.isCompatibleWith(contentType)) {
                        XmlFormat.merge(reader, this.extensionRegistry, builder);
                }
                else {
                        builder.mergeFrom(inputMessage.getBody(), this.extensionRegistry);
                }
                return builder.build();
        }
        catch (Exception e) {
                throw new HttpMessageNotReadableException("Could not read Protobuf message: " + e.getMessage(), e);
        }
}
 

实例 10


@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public ResponseEntity<ErrorMessage> handleException(
                HttpMessageNotReadableException ex, 
                HttpServletResponse response) {
    return getErrorResponse(ex.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
}
 

实例 11


protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
        try {
                Unmarshaller unmarshaller = createUnmarshaller(clazz);
                if (clazz.isAnnotationPresent(XmlRootElement.class)) {
                        return unmarshaller.unmarshal(source);
                }
                else {
                        JAXBElement jaxbElement = unmarshaller.unmarshal(source, clazz);
                        return jaxbElement.getValue();
                }
        }
        catch (UnmarshalException ex) {
                throw new HttpMessageNotReadableException("Could not unmarshal to [" + clazz + "]: " + ex.getMessage(), ex);
        }
        catch (JAXBException ex) {
                throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
        }
}
 

实例 12


@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException,
        HttpMessageNotReadableException {
        JavaType javaType = getJavaType(clazz, null);
        return readJavaType(javaType, inputMessage);
}
 

实例 13


@Override
public T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException,
                HttpMessageNotReadableException {
        String headerType = inputMessage.getHeaders().getFirst(HEADER_KEY);
        Class<? extends T> target = findHeaderMapping(headerType);
        if (target != null) {
                return super.read(target, inputMessage);
        }
        return super.read(clazz, inputMessage);
}
 

实例 14


@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
        HttpMessageNotReadableException ex, HttpHeaders headers,
        HttpStatus status, WebRequest request) {
    if (ex.getCause() instanceof Exception) {
        return handleExceptionInternal((Exception) ex.getCause(), null,
                headers, status, request);
    } else {
        return handleExceptionInternal(ex, null, headers, status, request);
    }
}
 

实例 15


@Override
public Request read(Class<? extends Request> type, HttpInputMessage him) throws IOException, HttpMessageNotReadableException {
        try {
                Deserializer deserializer = DeserializerFactory.getDeserializer(SerializationFormat.XML);
                return deserializer.getObjectFromMessage(him.getBody().toString(), Request.class);
        } catch (DeserializationException | UnsupportedSerializationFormatException ex) {
                throw new HttpMessageNotReadableException("The object could not be parsed from XML");
        }
}
 
讨论
淘淘あ西西 profile image