天天看點

Http發送請求時,如有多個Cookie,該如何擷取JSessionid

如題,很多時候當我們用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;
   }
}
           

嘿嘿,大概就是醬紫了,如有問題,還請各位大牛不吝賜教,就此謝過!