package com.lemon.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: Lemon
 * @description:
 * @author: ray
 * @create: 2022-09-26 10:30
 **/
public class AuthorizationCookieUtils {
    public static Map<String, String> cookies = new HashMap<>();
    public static final String RESPONSE_HEADER = "Set-Cookie";
    public static final String REQUEST_HEADER = "Cookie";
    public static final String COOKIE_NAME = "JSESSIONID";


    //抓取cookie存到cookie缓存中
    public static void getCookieByResponse(HttpResponse response) {
        //从响应头里面获取指定的头字段
        Header header = response.getFirstHeader(RESPONSE_HEADER);
        //如果header不为空
        if (header != null) {
            //获取头字段的值
            String cookie = header.getValue();
            //如果头字段的值不为空
            if (StringUtils.isNotBlank(cookie)) {
                String[] values = cookie.split(",");
                for (String value : values) {
                    //如果包含JSESSIONID那么放进缓存cookie之中
                    if (value.contains(COOKIE_NAME)) {
                        // 将得到cookie为JSESSIONID=03DECD00SXDXWSXFS
                        cookies.put(COOKIE_NAME, value);
                    }
                }
            }
        }
    }

    //从cookie缓存中取出cookie添加到请求头中
    public static void addCookieInRequest(HttpRequest request) {
        //从缓存中将cookie对应的值取出来
        String value = cookies.get(COOKIE_NAME);
        //如果cookie不为空，添加到请求头中
        if(StringUtils.isNotBlank(value)){
            request.setHeader(REQUEST_HEADER,value);
        }
    }


    public static void main(String[] args) {


    }
}
