Search in sources :

Example 1 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 2 with MediaType

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

the class FormHttpMessageConverter method read.

@Override
public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MediaType contentType = inputMessage.getHeaders().getContentType();
    Charset charset = (contentType.getCharset() != null ? contentType.getCharset() : this.charset);
    String body = StreamUtils.copyToString(inputMessage.getBody(), charset);
    String[] pairs = StringUtils.tokenizeToStringArray(body, "&");
    MultiValueMap<String, String> result = new LinkedMultiValueMap<>(pairs.length);
    for (String pair : pairs) {
        int idx = pair.indexOf('=');
        if (idx == -1) {
            result.add(URLDecoder.decode(pair, charset.name()), null);
        } else {
            String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
            String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
            result.add(name, value);
        }
    }
    return result;
}
Also used : LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) MediaType(org.springframework.http.MediaType) Charset(java.nio.charset.Charset)

Example 3 with MediaType

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

the class FormHttpMessageConverter method writeMultipart.

private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage) throws IOException {
    final byte[] boundary = generateMultipartBoundary();
    Map<String, String> parameters = Collections.singletonMap("boundary", new String(boundary, "US-ASCII"));
    MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
    HttpHeaders headers = outputMessage.getHeaders();
    headers.setContentType(contentType);
    if (outputMessage instanceof StreamingHttpOutputMessage) {
        StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
        streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {

            @Override
            public void writeTo(OutputStream outputStream) throws IOException {
                writeParts(outputStream, parts, boundary);
                writeEnd(outputStream, boundary);
            }
        });
    } else {
        writeParts(outputMessage.getBody(), parts, boundary);
        writeEnd(outputMessage.getBody(), boundary);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) StreamingHttpOutputMessage(org.springframework.http.StreamingHttpOutputMessage) OutputStream(java.io.OutputStream) MediaType(org.springframework.http.MediaType) IOException(java.io.IOException)

Example 4 with MediaType

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

the class AbstractJackson2HttpMessageConverter method writeInternal.

@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    MediaType contentType = outputMessage.getHeaders().getContentType();
    JsonEncoding encoding = getJsonEncoding(contentType);
    JsonGenerator generator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
    try {
        writePrefix(generator, object);
        Class<?> serializationView = null;
        FilterProvider filters = null;
        Object value = object;
        JavaType javaType = null;
        if (object instanceof MappingJacksonValue) {
            MappingJacksonValue container = (MappingJacksonValue) object;
            value = container.getValue();
            serializationView = container.getSerializationView();
            filters = container.getFilters();
        }
        if (type != null && value != null && TypeUtils.isAssignable(type, value.getClass())) {
            javaType = getJavaType(type, null);
        }
        ObjectWriter objectWriter;
        if (serializationView != null) {
            objectWriter = this.objectMapper.writerWithView(serializationView);
        } else if (filters != null) {
            objectWriter = this.objectMapper.writer(filters);
        } else {
            objectWriter = this.objectMapper.writer();
        }
        if (javaType != null && javaType.isContainerType()) {
            objectWriter = objectWriter.forType(javaType);
        }
        SerializationConfig config = objectWriter.getConfig();
        if (contentType != null && contentType.isCompatibleWith(MediaType.TEXT_EVENT_STREAM) && config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
            objectWriter = objectWriter.with(this.ssePrettyPrinter);
        }
        objectWriter.writeValue(generator, value);
        writeSuffix(generator, object);
        generator.flush();
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write content: " + ex.getMessage(), ex);
    }
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) JsonEncoding(com.fasterxml.jackson.core.JsonEncoding) SerializationConfig(com.fasterxml.jackson.databind.SerializationConfig) MediaType(org.springframework.http.MediaType) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FilterProvider(com.fasterxml.jackson.databind.ser.FilterProvider)

Example 5 with MediaType

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

the class Jaxb2CollectionHttpMessageConverter method canRead.

/**
	 * {@inheritDoc}
	 * <p>Jaxb2CollectionHttpMessageConverter can read a generic
	 * {@link Collection} where the generic type is a JAXB type annotated with
	 * {@link XmlRootElement} or {@link XmlType}.
	 */
@Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
    if (!(type instanceof ParameterizedType)) {
        return false;
    }
    ParameterizedType parameterizedType = (ParameterizedType) type;
    if (!(parameterizedType.getRawType() instanceof Class)) {
        return false;
    }
    Class<?> rawType = (Class<?>) parameterizedType.getRawType();
    if (!(Collection.class.isAssignableFrom(rawType))) {
        return false;
    }
    if (parameterizedType.getActualTypeArguments().length != 1) {
        return false;
    }
    Type typeArgument = parameterizedType.getActualTypeArguments()[0];
    if (!(typeArgument instanceof Class)) {
        return false;
    }
    Class<?> typeArgumentClass = (Class<?>) typeArgument;
    return (typeArgumentClass.isAnnotationPresent(XmlRootElement.class) || typeArgumentClass.isAnnotationPresent(XmlType.class)) && canRead(mediaType);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) XmlType(javax.xml.bind.annotation.XmlType) MediaType(org.springframework.http.MediaType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) XmlType(javax.xml.bind.annotation.XmlType)

Aggregations

MediaType (org.springframework.http.MediaType)481 Test (org.junit.jupiter.api.Test)177 HttpHeaders (org.springframework.http.HttpHeaders)97 Test (org.junit.Test)61 ArrayList (java.util.ArrayList)58 Charset (java.nio.charset.Charset)42 MockHttpOutputMessage (org.springframework.http.MockHttpOutputMessage)34 List (java.util.List)33 MockHttpInputMessage (org.springframework.http.MockHttpInputMessage)33 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)33 HashMap (java.util.HashMap)30 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)30 IOException (java.io.IOException)26 Resource (org.springframework.core.io.Resource)23 ResolvableType (org.springframework.core.ResolvableType)22 HttpEntity (org.springframework.http.HttpEntity)21 ServerWebExchange (org.springframework.web.server.ServerWebExchange)20 MockServerWebExchange (org.springframework.web.testfixture.server.MockServerWebExchange)20 Nullable (org.springframework.lang.Nullable)18 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)18