zoukankan      html  css  js  c++  java
  • 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详细使用示例

     
  • 相关阅读:
    (总结)Nginx/LVS/HAProxy负载均衡软件的优缺点详解
    一个自动安装LNMP的简洁Shell脚本
    (总结)Nginx配置文件nginx.conf中文详解
    Linux 的启动流程
    Linux运维文档之nginx
    nginx索引目录配置
    nginx实现图片防盗链(referer指令)
    nginx记录分析网站响应慢的请求(ngx_http_log_request_speed)
    C# 使用WinRar命令压缩和解压缩
    localStorage存值取值以及存取JSON,以及基于html5 localStorage的购物车
  • 原文地址:https://www.cnblogs.com/yadongliang/p/13653323.html
Copyright © 2011-2022 走看看