如何实现对openfeign的请求request和响应response的拦截

  • 通过实现对openfeign的请求request和响应response的拦截,可以在request和response添加自定义的需求及业务

  • 拦截openfeign的请求,并添加业务


import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.micrometer.core.instrument.util.StringUtils;
import io.seata.core.context.RootContext;

@Configuration
public class ComonConfig {

	@Bean
	public RequestInterceptor requestInterceptor() {
		return new RequestInterceptor() {
			@Override
			public void apply(RequestTemplate requestTemplate) {
				ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
						.getRequestAttributes();
				HttpServletRequest request = attributes.getRequest(); // 老 request
				
	            // 从Seata获取XID,并将其添加到Feign请求标头中
	            String xid = RootContext.getXID();
	            if (xid != null) {
	                requestTemplate.header("TX_XID", xid);
	            }
				
				requestTemplate.header("Cookie", request.getHeader("Cookie")); // 新request
				String pageSizeDefault = "20";
				String pageNumDefalut = "1";
				String pageSize = request.getParameter("pageSize");
				String pageNum = request.getParameter("pageNum");
				if (StringUtils.isNotEmpty(pageSize)) {
					pageSizeDefault = pageSize;
				}
				if (StringUtils.isNotEmpty(pageNum)) {
					pageNumDefalut = pageNum;
				}
				requestTemplate.header("pageSize", pageSizeDefault);
				requestTemplate.header("pageNum", pageNumDefalut);
//				requestTemplate.header("Accept", "application/json;charset=UTF-8");
//				requestTemplate.header("Content-Type", "application/json;charset=UTF-8");
			}
		};
	}
}

  • 拦截openfeign的响应,并添加业务
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

@Configuration
public class FeignOkHttpClientConfig {


//	private static int MAX_RETRY = 10;

	@Bean
	public OkHttpClient.Builder okHttpClientBuilder() {
		return new OkHttpClient.Builder().addInterceptor(new FeignOkHttpClientResponseInterceptor());
	}

	public static class FeignOkHttpClientResponseInterceptor implements Interceptor {

		Logger logger = LoggerFactory.getLogger(this.getClass());

		@Override
		public Response intercept(Chain chain) throws IOException {

//			int retryNum = 0;

			Request originalRequest = chain.request();
			Response response = chain.proceed(originalRequest);
			String checkNo = response.header("checkNo");
			String contentBase64 = response.header("content");
			String audit = response.header("audit");
			String contentOrigin = "";
			if (contentBase64 != null) {
				contentOrigin = new String(Base64.decodeBase64(contentBase64), "UTF-8");
			}
			MediaType mediaType = response.body().contentType();
			// 解析bodyContent,做你想做的事情!!
			String bodyContent = response.body().string();
			
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
					.getRequest();
			request.setAttribute("checkNo", checkNo);
			request.setAttribute("content", contentOrigin);
			request.setAttribute("audit", audit);
			// ===================================================
			int endRow = 0;
			if (response.header("endRow") != null) {
				endRow = Integer.parseInt(response.header("endRow"));
			}
			int firstPage = 0;
			if (response.header("firstPage") != null) {
				firstPage = Integer.parseInt(response.header("firstPage"));
			}
			int lastPage = 0;
			if (response.header("lastPage") != null) {
				lastPage = Integer.parseInt(response.header("lastPage"));
			}
			int navigateFirstPage = 0;
			if (response.header("navigateFirstPage") != null) {
				navigateFirstPage = Integer.parseInt(response.header("navigateFirstPage"));
			}
			int navigateLastPage = 0;
			if (response.header("navigateLastPage") != null) {
				navigateLastPage = Integer.parseInt(response.header("navigateLastPage"));
			}
//			int[] navigatepageNums = Integer.parseInt(response.header("navigatepageNums"));
			int navigatePages = 0;
			if (response.header("navigatePages") != null) {
				navigatePages = Integer.parseInt(response.header("navigatePages"));
			}
			int nextPage = 0;
			if (response.header("nextPage") != null) {
				nextPage = Integer.parseInt(response.header("nextPage"));
			}
			int pageNum = 0;
			if (response.header("pageNum") != null) {
				pageNum = Integer.parseInt(response.header("pageNum"));
			}
			int pages = 0;
			if (response.header("pages") != null) {
				pages = Integer.parseInt(response.header("pages"));
			}
			int pageSize = 0;
			if (response.header("pageSize") != null) {
				pageSize = Integer.parseInt(response.header("pageSize"));
			}
			int prePage = 0;
			if (response.header("prePage") != null) {
				prePage = Integer.parseInt(response.header("prePage"));
			}
			int size = 0;
			if (response.header("size") != null) {
				size = Integer.parseInt(response.header("size"));
			}
			int startRow = 0;
			if (response.header("startRow") != null) {
				startRow = Integer.parseInt(response.header("startRow"));
			}
			int total = 0;
			if (response.header("total") != null) {
				total = Integer.parseInt(response.header("total"));
			}
			Map<String, Integer> pagesMap = new HashMap<String, Integer>();
			pagesMap.put("endRow", endRow);
			pagesMap.put("firstPage", firstPage);
			pagesMap.put("lastPage", lastPage);
			pagesMap.put("navigateFirstPage", navigateFirstPage);
			pagesMap.put("navigateLastPage", navigateLastPage);
			pagesMap.put("navigatePages", navigatePages);
			pagesMap.put("nextPage", nextPage);
			pagesMap.put("pageNum", pageNum);
			pagesMap.put("pages", pages);
			pagesMap.put("pageSize", pageSize);
			pagesMap.put("prePage", prePage);
			pagesMap.put("size", size);
			pagesMap.put("startRow", startRow);
			pagesMap.put("total", total);
			ThreadLocalCommon.pageIn.set(pagesMap);
			// 生成新的response返回,网络请求的response如果取出之后,直接返回将会抛出异常
			return response.newBuilder().body(ResponseBody.create(mediaType, bodyContent)).build();
		}
	}
}

你可能感兴趣的:(openfeign,请求拦截器,响应拦截器)