我需要通过内容类型为MultiValueMapRestTemplate发布对象(例如,不是application/x-www-form-urlencoded)。当我尝试这样做时...

HttpHeaders headers = new HttpHeaders();
HttpEntity request;

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED)

// data is some generic type
request = new HttpEntity<>(data, headers);

// clazz is the Class<T> being returned
restTemplate.exchange(url, method, request, clazz)

...我收到以下错误:



这是我在restTemplate.getMessageConverters()中看到的内容:

java - 将RestTemplate与对象一起用作数据和application/x-www-form-urlencoded内容类型?-LMLPHP

为什么我不想提供MultiValueMap?两个原因:
  • 这是通用代码,用于将请求发送到多个端点,因此添加专门用于x-www-form-urlencoded的重载只会使
  • 复杂化
  • 似乎不是必须的-我只是不知道需要使用哪个HttpMessageConverter来支持将对象转换为x-www-form-urlencoded字符串
  • 最佳答案

    我最终不得不编写一个自定义HTTP消息转换器,该转换器接收任何对象并将其作为www-form-urlencoded内容写到请求主体中:

    用法

    RestTemplate template = new RestTemplate(...);
    
    template.getMessageConverters().add(new ObjectToUrlEncodedConverter(mapper));
    

    ObjectToUrlEncodedConverter

    import com.fasterxml.jackson.annotation.JsonAnySetter;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.http.HttpInputMessage;
    import org.springframework.http.HttpOutputMessage;
    import org.springframework.http.MediaType;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.HttpMessageNotReadableException;
    import org.springframework.http.converter.HttpMessageNotWritableException;
    import sun.reflect.generics.reflectiveObjects.NotImplementedException;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.util.Collections;
    import java.util.List;
    
    public class ObjectToUrlEncodedConverter implements HttpMessageConverter
    {
        private static final String Encoding = "UTF-8";
    
        private final ObjectMapper mapper;
    
        public ObjectToUrlEncodedConverter(ObjectMapper mapper)
        {
            this.mapper = mapper;
        }
    
        @Override
        public boolean canRead(Class clazz, MediaType mediaType)
        {
            return false;
        }
    
        @Override
        public boolean canWrite(Class clazz, MediaType mediaType)
        {
            return getSupportedMediaTypes().contains(mediaType);
        }
    
        @Override
        public List<MediaType> getSupportedMediaTypes()
        {
            return Collections.singletonList(MediaType.APPLICATION_FORM_URLENCODED);
        }
    
        @Override
        public Object read(Class clazz, HttpInputMessage inputMessage) throws HttpMessageNotReadableException
        {
            throw new NotImplementedException();
        }
    
        @Override
        public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException
        {
            if (o != null)
            {
                String body = mapper
                    .convertValue(o, UrlEncodedWriter.class)
                    .toString();
    
                try
                {
                    outputMessage.getBody().write(body.getBytes(Encoding));
                }
                catch (IOException e)
                {
                    // if UTF-8 is not supporter then I give up
                }
            }
        }
    
        private static class UrlEncodedWriter
        {
            private final StringBuilder out = new StringBuilder();
    
            @JsonAnySetter
            public void write(String name, Object property) throws UnsupportedEncodingException
            {
                if (out.length() > 0)
                {
                    out.append("&");
                }
    
                out
                    .append(URLEncoder.encode(name, Encoding))
                    .append("=");
    
                if (property != null)
                {
                    out.append(URLEncoder.encode(property.toString(), Encoding));
                }
            }
    
            @Override
            public String toString()
            {
                return out.toString();
            }
        }
    }
    

    10-06 02:22