HttpClient发起请求,将响应结果(header和entity)设置到response中返回

前言

HttpClient发起请求,将响应结果(header和entity)设置到response中返回

package com.graph.oss.config;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.graph.atlas.common.base.util.JSONUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

//import org.apache.tomcat.util.buf.MessageBytes;

/**
 * 对象服务接口透传 只有非控制接口(/oss/*)才会进到这个拦截器
 */
public class ContentInterceptor extends HandlerInterceptorAdapter {

    private static final String PATH_DELIMITER = "/";
    private OssServerConfig ossServerConfig;
    private MinioServerConfig minioServerConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        // get配置文件bean
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        ossServerConfig = (OssServerConfig) factory.getBean("ossServerConfig");
        minioServerConfig = (MinioServerConfig) factory.getBean("minioServerConfig");

        // get request uri(undertow)
        String uri = request.getRequestURI();

        // uri处理(去掉context.api)
        String api = ossServerConfig.getApi();
        if (uri.startsWith(api)) {
            uri = uri.replace(api, PATH_DELIMITER);
        }

        // get httpclient response
        String minioUrl = minioServerConfig.getEndpoint() + uri;

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(minioUrl);

        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(10 * 1000).build();

        httpGet.setConfig(config);
        httpGet.addHeader("content-type", "application/json");
        CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpGet);
        ServletOutputStream out = null;
        try {
            // 将httpClient响应的header和entity设置到httpServletResponse
            Header header = closeableHttpResponse.getFirstHeader("Content-Type");
            response.setHeader(header.getName(), header.getValue());
            HttpEntity entity = closeableHttpResponse.getEntity();
            out = response.getOutputStream();
            entity.writeTo(out);
            out.flush();
            out.close();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    // 根据Field获得对应的Class
    private Class getClassByName(Class classObject, String name) {
        Map<Class, List<Field>> fieldMap = new HashMap<>();
        Class returnClass = null;
        Class tempClass = classObject;
        while (tempClass != null) {
            fieldMap.put(tempClass, Arrays.asList(tempClass.getDeclaredFields()));
            tempClass = tempClass.getSuperclass();
        }

        for (Map.Entry<Class, List<Field>> entry : fieldMap.entrySet()) {
            for (Field f : entry.getValue()) {
                if (f.getName().equals(name)) {
                    returnClass = entry.getKey();
                    break;
                }
            }
        }
        return returnClass;
    }

    // 递归遍历父类寻找coyoteRequest Field
    private Object findCoyoteRequest(Object request) throws Exception {
        Class a = getClassByName(request.getClass(), "request");
        Field request1 = a.getDeclaredField("request");
        request1.setAccessible(true);
        Object b = request1.get(request);
        if (getClassByName(b.getClass(), "coyoteRequest") == null) {
            return findCoyoteRequest(b);
        } else {
            return b;
        }
    }

    private String getReqStr(String namespace, String prefix, String name) {
        Map<String, String> map = new HashMap<>();
        map.put("namespace", namespace);
        map.put("prefix", prefix);
        map.put("fileName", name);
        return JSONUtils.toJSONString(map);
    }
}

 

感谢

https://blog.csdn.net/GY325416/article/details/81436078

HttpClient详细使用示例

 

 
posted @ 2020-09-11 18:30  习惯沉淀  阅读(4725)  评论(0编辑  收藏  举报