Search in sources :

Example 31 with MediaType

use of org.springframework.http.MediaType in project spring-framework by spring-projects.

the class AbstractHttpReceivingTransportHandler method handleRequestInternal.

protected void handleRequestInternal(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, AbstractHttpSockJsSession sockJsSession) throws SockJsException {
    String[] messages;
    try {
        messages = readMessages(request);
    } catch (IOException ex) {
        logger.error("Failed to read message", ex);
        if (ex.getClass().getName().contains("Mapping")) {
            // e.g. Jackson's JsonMappingException, indicating an incomplete payload
            handleReadError(response, "Payload expected.", sockJsSession.getId());
        } else {
            handleReadError(response, "Broken JSON encoding.", sockJsSession.getId());
        }
        return;
    } catch (Throwable ex) {
        logger.error("Failed to read message", ex);
        handleReadError(response, "Failed to read message(s)", sockJsSession.getId());
        return;
    }
    if (messages == null) {
        handleReadError(response, "Payload expected.", sockJsSession.getId());
        return;
    }
    if (logger.isTraceEnabled()) {
        logger.trace("Received message(s): " + Arrays.asList(messages));
    }
    response.setStatusCode(getResponseStatus());
    response.getHeaders().setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
    sockJsSession.delegateMessages(messages);
}
Also used : MediaType(org.springframework.http.MediaType) IOException(java.io.IOException)

Example 32 with MediaType

use of org.springframework.http.MediaType in project spring-framework by spring-projects.

the class JsonpReceivingTransportHandler method readMessages.

@Override
protected String[] readMessages(ServerHttpRequest request) throws IOException {
    SockJsMessageCodec messageCodec = getServiceConfig().getMessageCodec();
    MediaType contentType = request.getHeaders().getContentType();
    if (contentType != null && MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) {
        MultiValueMap<String, String> map = this.formConverter.read(null, request);
        String d = map.getFirst("d");
        return (StringUtils.hasText(d) ? messageCodec.decode(d) : null);
    } else {
        return messageCodec.decodeInputStream(request.getBody());
    }
}
Also used : MediaType(org.springframework.http.MediaType) SockJsMessageCodec(org.springframework.web.socket.sockjs.frame.SockJsMessageCodec)

Example 33 with MediaType

use of org.springframework.http.MediaType in project springboot_op by SnailFastGo.

the class FastJsonConfiguration method configureMessageConverters.

/**
     * 修改自定义消息转换器
     * @param converters 消息转换器列表
     */
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //调用父类的配置
    super.configureMessageConverters(converters);
    //创建fastJson消息转换器
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    //处理中文乱码问题
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastConverter.setSupportedMediaTypes(fastMediaTypes);
    //创建配置类
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    //修改配置返回内容的过滤
    fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
    fastConverter.setFastJsonConfig(fastJsonConfig);
    //将fastjson添加到视图消息转换器列表内
    converters.add(fastConverter);
}
Also used : FastJsonConfig(com.alibaba.fastjson.support.config.FastJsonConfig) ArrayList(java.util.ArrayList) FastJsonHttpMessageConverter(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter) MediaType(org.springframework.http.MediaType)

Example 34 with MediaType

use of org.springframework.http.MediaType in project fastjson by alibaba.

the class FastJsonpResponseBodyAdvice method beforeBodyWriteInternal.

/**
     * Invoked only if the converter type is {@code FastJsonpHttpMessageConverter4}.
     */
public void beforeBodyWriteInternal(MappingFastJsonValue bodyContainer, MediaType contentType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    for (String name : this.jsonpQueryParamNames) {
        String value = servletRequest.getParameter(name);
        if (value != null) {
            if (!isValidJsonpQueryParam(value)) {
                continue;
            }
            MediaType contentTypeToUse = getContentType(contentType, request, response);
            response.getHeaders().setContentType(contentTypeToUse);
            bodyContainer.setJsonpFunction(value);
            break;
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) MediaType(org.springframework.http.MediaType)

Example 35 with MediaType

use of org.springframework.http.MediaType in project fastjson by alibaba.

the class FastJsonHttpMessageConverterTest method test_read.

@SuppressWarnings("deprecation")
public void test_read() throws Exception {
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    converter.setCharset(Charset.forName("UTF-8"));
    Assert.assertEquals(Charset.forName("UTF-8"), converter.getCharset());
    converter.setFeatures(SerializerFeature.BrowserCompatible);
    Assert.assertEquals(1, converter.getFeatures().length);
    Assert.assertEquals(SerializerFeature.BrowserCompatible, converter.getFeatures()[0]);
    Assert.assertNull(converter.getDateFormat());
    converter.setDateFormat("yyyyMMdd");
    converter.setFilters(serializeFilter);
    Assert.assertEquals(1, converter.getFilters().length);
    Assert.assertEquals(serializeFilter, converter.getFilters()[0]);
    converter.addSerializeFilter(serializeFilter);
    Assert.assertEquals(2, converter.getFilters().length);
    converter.addSerializeFilter(null);
    converter.setSupportedMediaTypes(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON_UTF8 }));
    Assert.assertEquals(1, converter.getSupportedMediaTypes().size());
    Method method = FastJsonHttpMessageConverter.class.getDeclaredMethod("supports", Class.class);
    method.setAccessible(true);
    method.invoke(converter, int.class);
    HttpInputMessage input = new HttpInputMessage() {

        public HttpHeaders getHeaders() {
            // TODO Auto-generated method stub
            return null;
        }

        public InputStream getBody() throws IOException {
            return new ByteArrayInputStream("{\"id\":123}".getBytes(Charset.forName("UTF-8")));
        }
    };
    VO vo = (VO) converter.read(VO.class, input);
    Assert.assertEquals(123, vo.getId());
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    HttpOutputMessage out = new HttpOutputMessage() {

        public HttpHeaders getHeaders() {
            return new HttpHeaders();
        }

        public OutputStream getBody() throws IOException {
            return byteOut;
        }
    };
    converter.write(vo, MediaType.TEXT_PLAIN, out);
    byte[] bytes = byteOut.toByteArray();
    Assert.assertEquals("{\"id\":\"123\"}", new String(bytes, "UTF-8"));
}
Also used : HttpInputMessage(org.springframework.http.HttpInputMessage) HttpHeaders(org.springframework.http.HttpHeaders) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpOutputMessage(org.springframework.http.HttpOutputMessage) FastJsonHttpMessageConverter(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter) MediaType(org.springframework.http.MediaType) Method(java.lang.reflect.Method) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

MediaType (org.springframework.http.MediaType)254 Test (org.junit.Test)157 HttpHeaders (org.springframework.http.HttpHeaders)49 MockHttpInputMessage (org.springframework.http.MockHttpInputMessage)31 MockHttpOutputMessage (org.springframework.http.MockHttpOutputMessage)24 Charset (java.nio.charset.Charset)21 ArrayList (java.util.ArrayList)21 URI (java.net.URI)20 ByteArrayInputStream (java.io.ByteArrayInputStream)15 IOException (java.io.IOException)15 ServerWebExchange (org.springframework.web.server.ServerWebExchange)15 List (java.util.List)14 HttpInputMessage (org.springframework.http.HttpInputMessage)14 HttpStatus (org.springframework.http.HttpStatus)11 Resource (org.springframework.core.io.Resource)10 HttpEntity (org.springframework.http.HttpEntity)10 HttpMessageNotReadableException (org.springframework.http.converter.HttpMessageNotReadableException)10 HttpMediaTypeNotAcceptableException (org.springframework.web.HttpMediaTypeNotAcceptableException)9 InputStream (java.io.InputStream)8 InputStreamReader (java.io.InputStreamReader)8