美文网首页
Feign如何支持Get请求传RequestBody

Feign如何支持Get请求传RequestBody

作者: 艺术类架构师 | 来源:发表于2019-08-24 23:40 被阅读0次

在使用Feign进行微服务互相调用的过程中,我们会碰到一个问题就是:Get请求时不能像SpringMVC中的RequestMapping一样直接接受对象,而在Feign中这样使用的话会将Get请求转换为Post请求方式,从而导致调用异常!

如何解决?

跟踪源代码,发现有个Encoder接口,它的作用是:

Encodes an object into an HTTP request body. Like javax.websocket.Encoder. Encoder is used when a method parameter has no @Param annotation. For example:
@POST
@Path("/")
void create(User user


默认spring-cloud-netflix-core里有一个SpringEncoder,并配置在FeignClientsConfiguration中,怎么办?
自定义一个就好了,只需要实现这个接口并覆盖原来的Encoder即可。
代码不是关键,关键是思路。如下的代码可以直接放生产环境使用

/*
 * Copyright 2013-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package custom;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import demo.RequestBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import static custom.FeignUtils.getHeaders;
import static custom.FeignUtils.getHttpHeaders;

/**
 * @author Spencer Gibb
 * @author Lycol
 * @purpose for support request by get that can be send with requestbody 
 */
public class MySpringEncoder implements Encoder {

    Logger log= LoggerFactory.getLogger(MySpringEncoder.class);
    private ObjectFactory<HttpMessageConverters> messageConverters;

    public MySpringEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        this.messageConverters = messageConverters;
    }

    @Override
    public void encode(Object requestBody, Type bodyType, RequestTemplate request)
            throws EncodeException {
        // template.body(conversionService.convert(object, String.class));
        if (requestBody != null) {
            Class<?> requestType = requestBody.getClass();
            Collection<String> contentTypes = request.headers().get("Content-Type");

            MediaType requestContentType = null;
            if (contentTypes != null && !contentTypes.isEmpty()) {
                String type = contentTypes.iterator().next();
                requestContentType = MediaType.valueOf(type);
            }

            for (HttpMessageConverter<?> messageConverter : this.messageConverters
                    .getObject().getConverters()) {
                if (messageConverter.canWrite(requestType, requestContentType)) {
                    if (log.isDebugEnabled()) {
                        if (requestContentType != null) {
                            log.debug("Writing [" + requestBody + "] as \""
                                    + requestContentType + "\" using ["
                                    + messageConverter + "]");
                        }
                        else {
                            log.debug("Writing [" + requestBody + "] using ["
                                    + messageConverter + "]");
                        }

                    }

                    FeignOutputMessage outputMessage = new FeignOutputMessage(request);
                    try {
                        @SuppressWarnings("unchecked")
                        HttpMessageConverter<Object> copy = (HttpMessageConverter<Object>) messageConverter;
                        copy.write(requestBody, requestContentType, outputMessage);
                    }
                    catch (IOException ex) {
                        throw new EncodeException("Error converting request body", ex);
                    }
                    // clear headers
                    request.headers(null);
                    System.out.println(request.method().equals(HttpMethod.GET.name())+"-------------");
                    // converters can modify headers, so update the request
                    // with the modified headers
                    request.headers(getHeaders(outputMessage.getHeaders()));
                    if(request.method().equals(HttpMethod.GET.name())){
                    if(requestBody !=null) {
                        Map<String, Object> requestMap = objectToMap(requestBody);
                        for (Map.Entry entry : requestMap.entrySet()) {
                            if (null != entry.getValue()) {
                                request.query(entry.getKey().toString(), entry.getValue().toString());
                            }
                        }
                    }

                    }
                    if(request.method().equals(HttpMethod.GET.name())) {
                     request.body(null);
                    }
                    else {
                        request.body(outputMessage.getOutputStream().toByteArray(),
                                Charset.forName("UTF-8")); // TODO: set charset
                    }
                    return;
                }
            }
            String message = "Could not write request: no suitable HttpMessageConverter "
                    + "found for request type [" + requestType.getName() + "]";
            if (requestContentType != null) {
                message += " and content type [" + requestContentType + "]";
            }
            throw new EncodeException(message);
        }
    }

    private class FeignOutputMessage implements HttpOutputMessage {

        private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        private final HttpHeaders httpHeaders;

        private FeignOutputMessage(RequestTemplate request) {
            httpHeaders = getHttpHeaders(request.headers());
        }

        @Override
        public OutputStream getBody() throws IOException {
            return this.outputStream;
        }

        @Override
        public HttpHeaders getHeaders() {
            return this.httpHeaders;
        }

        public ByteArrayOutputStream getOutputStream() {
            return this.outputStream;
        }

    }

    private static Map<String,Object> objectToMap(Object requestBody){
        ObjectMapper objectMapper=new ObjectMapper();
        Map<String, Object> objectAsMap = objectMapper.convertValue(requestBody, Map.class);
        return  objectAsMap;
    }

}


配置Configuration

package custom;

import feign.codec.Encoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.cloud.netflix.feign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by Administrator on 2019/8/24.
 */
@Configuration
public class SpringDecoderConfiguration {


    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder feignEncoder() {
        return new MySpringEncoder(this.messageConverters);
    }
}

相关文章

网友评论

      本文标题:Feign如何支持Get请求传RequestBody

      本文链接:https://www.haomeiwen.com/subject/ifpcectx.html