如题,很多时候当我们用Http发送请求时,会有多个Cookie,这时该如何获取JSessionid呢?话不多说,直接上代码:

static CookieManager cookieManager = new CookieManager();
            CookieHandler.setDefault(cookieManager);
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
            //这里通过cookieStore.getCookies可以获得请求过程中的所有Cookie
            CookieStore cookieStore = cookieManager.getCookieStore();
            List<HttpCookie> cookies = cookieStore.getCookies();
            //这里通过获取每一个Cookie,然后根据实际需要,获取token、JSESSIONID等信息
            HttpCookie httpCookie = cookies.get(0);
            HttpCookie httpCookie1 = cookies.get(1);
            token = httpCookie.getValue();
            JSESSIONID = httpCookie1.getValue();
            Cookie = "JSESSIONID=" + JSESSIONID + "; X-Uni-Crsf-Token=" + token;
            headerField = conn.getHeaderField("Set-Cookie");

下面,模拟一下利用HttpsURLConnection发送一个Post的登录请求,然后获取登录响应后的token和JSESSIONID信息,写入到下一次请求的请求头中,让其在请求时带上,并执行该请求,以下是所有代码:

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.List;

public class PostUtils {
    private static String LOGIN_URL = "https://localhost:8080/login";
    private static String CONNECT_URL = "https://localhost:8080/login/connect";
    private static String token = "";
    private static String JSESSIONID = "";
    private static String Cookie = "";
    private static String headerField = "";
    static CookieManager cookieManager = new CookieManager();

public static void main(String[] args) {
    String loginMessage = Login("admin", "123456");
    System.out.println(loginMessage);
    String connectMessage = connect("10.168.36.88","8888");
    System.out.println(connectMessage);
}

private static String Login(String username,String password) {
    {
        String msg = "";
        try{

            CookieHandler.setDefault(cookieManager);
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

            HttpURLConnection conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
            //设置请求方式,请求超时信息
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            //设置运行输入,输出:
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //Post方式不能缓存,需手动设置为false
            conn.setUseCaches(false);
            //设置请求头的信息,根据实际情况,选择需要的信息,可能还会需要Host、Origin、Referer、User-Agent等信息
            conn.setRequestProperty("Accept","image/webp,image/apng,image/*,*/*;q=0.8");
            conn.setRequestProperty("Connection","keep-alive");
            conn.setRequestProperty("Content-Type","application/x-java-serialized-object");

            //请求的数据:
            String data = "username=" + URLEncoder.encode(username, "UTF-8") +
                    "&password=" + URLEncoder.encode(password, "UTF-8");
            conn.connect();

            //获取输出流
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.flush();

            if (conn.getResponseCode() == 200) {
                // 获取响应的输入流对象
                InputStream is = conn.getInputStream();
                // 创建字节输出流对象
                ByteArrayOutputStream message = new ByteArrayOutputStream();
                // 定义读取的长度
                int len = 0;
                // 定义缓冲区
                byte buffer[] = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = is.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    message.write(buffer, 0, len);
                }
                // 释放资源
                is.close();
                message.close();

                //这里通过cookieStore.getCookies可以获得请求过程中的所有Cookie
                CookieStore cookieStore = cookieManager.getCookieStore();
                List<HttpCookie> cookies = cookieStore.getCookies();
                //这里通过获取每一个Cookie,然后根据实际需要,获取token、JSESSIONID等信息
                HttpCookie httpCookie = cookies.get(0);
                HttpCookie httpCookie1 = cookies.get(1);
                token = httpCookie.getValue();
                JSESSIONID = httpCookie1.getValue();
                Cookie = "JSESSIONID=" + JSESSIONID + "; X-Uni-Crsf-Token=" + token;
                headerField = conn.getHeaderField("Set-Cookie");

                // 返回字符串
                msg = new String(message.toByteArray());
                return msg;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return msg;
    }
}

private static String connect(String ip,String port) {
    String msg = "";
    try{

        HttpURLConnection conn = (HttpURLConnection) new URL(CONNECT_URL).openConnection();
        //设置请求方式,请求超时信息
        conn.setRequestMethod("POST");
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        //设置运行输入,输出:
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //Post方式不能缓存,需手动设置为false
        conn.setUseCaches(false);
        //设置请求头的信息,根据实际情况,选择需要的信息,可能还会需要Host、Origin、Referer、User-Agent等信息
        conn.setRequestProperty("Accept","image/webp,image/apng,image/*,*/*;q=0.8");
        conn.setRequestProperty("Connection","keep-alive");
        conn.setRequestProperty("Content-Type","application/x-java-serialized-object");

        //将上一次响应里返回的token和JSESSIONID信息写入请求头,在下一次请求时带上,这一步很关键
        conn.setRequestProperty("X-Uni-Crsf-Token",token);
        conn.setRequestProperty("Cookie",Cookie);

        //请求的数据:这里如果前端接收的是json,则可以将String转换成json再通过IO流写入
        String data = "ip=" + URLEncoder.encode(ip, "UTF-8") +
                "&port=" + URLEncoder.encode(port, "UTF-8");
        conn.connect();

        //获取输出流
        OutputStream out = conn.getOutputStream();
        out.write(data.getBytes());
        out.flush();

        if (conn.getResponseCode() == 200) {
            // 获取响应的输入流对象
            InputStream is = conn.getInputStream();
            // 创建字节输出流对象
            ByteArrayOutputStream message = new ByteArrayOutputStream();
            // 定义读取的长度
            int len = 0;
            // 定义缓冲区
            byte buffer[] = new byte[1024];
            // 按照缓冲区的大小,循环读取
            while ((len = is.read(buffer)) != -1) {
                // 根据读取的长度写入到os对象中
                message.write(buffer, 0, len);
            }
            // 释放资源
            is.close();
            message.close();

            // 返回字符串
            msg = new String(message.toByteArray());
            return msg;
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return msg;
   }
}

嘿嘿,大概就是酱紫了,如有问题,还请各位大牛不吝赐教,就此谢过!