cglib应用

package com.theorydance.myshare.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.grand.common.utils.Tools;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 对HttpRequest的execute进行了控制执行,满足规则才会进行真实请求的发送
 */
public class CustomHttpRequest2 extends HttpRequest {

	/**
	 * 表示环境:prod表示正式环境,这个变量允许通过外部进行设置
	 */
    public static String env = "prod";
    
    /**
     * http请求地址的url参数
     */
    private String url;

    /**
     * 构造
     */
    public CustomHttpRequest2(String url) {
        super(url);
        this.url = url;
    }

    /**
     * 构造一个POST请求
     */
    public static HttpRequest post(String url) {
        return new CustomHttpRequest2(url).method(Method.POST);
    }
    
    /**
     * 构造一个GET请求
     */
    public static HttpRequest get(String url) {
        return new CustomHttpRequest2(url).method(Method.GET);
    }
    
    @Override
    public HttpResponse execute() {
        System.out.println("this.url = " + this.url);
        // 如果是正式环境,就将http真实请求发送出去
        if (env.equalsIgnoreCase("prod")){
            return super.execute();
        } else {
        	// 非正式环境,真实http请求不会发送,下面的目的是为了模拟构造一个HttpResponse响应内容,这种情况下返回的状态码为501
            try {
                HttpResponse response = HttpRequest.post("http://www.baidu.com/search").timeout(2000).execute();
                Field statusField = response.getClass().getDeclaredField("status");
                statusField.setAccessible(true);
                statusField.set(response, 501);
                return response;
            } catch (Exception e) {
                return null;
            }
        }
    }

    /**
     * 请求示例
     */
    public static void main(String[] args) {
    	// CustomHttpRequest2.env属性的设置,应该在spring项目启动的时候,从配置文件种读取,然后全局修改
        CustomHttpRequest2.env = "test";
        
        // 真实示例请求
        HttpResponse response = CustomHttpRequest2.post("http://www.baidu.com/search")
                .header("token", "123456")
                .timeout(2000)
                .execute();
        // 正常的http请求使用,一般是要求先判断响应码是否正确响应,然后才会考虑是否读取响应内容
        System.out.println("response.getStatus() = " + response.getStatus());
    }
}
posted @ 2022-06-14 22:15  理舞  阅读(24)  评论(0编辑  收藏  举报