使用 RestTemplate 和对象作为数据和应用程序/x-www-form-urlencoded 内容类型?

2022-09-03 01:05:04

我需要通过内容类型的a发布一个对象(例如不是a)。当我尝试这样做时...MultiValueMapRestTemplateapplication/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)

...我收到以下错误:

org.springframework.web.client.RestClientException: Can not write request: no 合适的 HttpMessageConverter for request type [com.whatever.MyRequestPayload] 和 content type [application/x-www-form-urlencoded]

以下是我在其中看到的:restTemplate.getMessageConverters()

message converters

为什么我不想提供多值地图原因有二:

  1. 这是用于向多个端点发送请求的通用代码,因此专门为添加重载只会使事情复杂化x-www-form-urlencoded
  2. 这似乎不是我应该做的 - 我只是不知道需要使用哪个HttpMessageConverter来支持将对象转换为字符串x-www-form-urlencoded

答案 1

我最终不得不编写一个自定义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();
        }
    }
}

答案 2

原因:没有转换器可以将您的java对象转换为格式的请求正文。x-www-form-urlencoded

解决方案1:创建这种转换器,如@Josh M.所发布的那样。

解决方案2:将java对象转换为,并且已经有一个名为spring boot的转换器,它将自动转换为格式的请求正文。MultiValueMapFormHttpMessageConverterMultiValueMapx-www-form-urlencoded

因此,在解决方案2中,您只需要将java对象转换为:MultiValueMap

        MultiValueMap<String, String> bodyPair = new LinkedMultiValueMap();
        bodyPair.add(K1, V1);
        bodyPair.add(K1, V2);
        bodyPair.add(K2, V2);
        ...

K1、 、 、 、 ..., 表示 java 对象中的字段名称和相应值。需要添加您在 java 类中声明的所有字段。如果字段太多,请考虑使用 Java 反射。V1K2V2


推荐