Not sure if this is the best way, but what helped me achieve this is the CloseableHttpClient class, which along with BasicCookieStore saves cookies for subsequent requests after login, implemented below:
BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpUriRequest login = RequestBuilder.post() .setUri(new URI(url_login)) .addParameter("login", "loginuname") .addParameter("password", "pwd") .addParameter("submit", "sub_mit"); CloseableHttpResponse response = httpclient.execute(login); List<Cookie> cookies = cookieStore.getCookies(); response.close(); HttpGet httpget2 = new HttpGet(url_to_get_after_login); CloseableHttpResponse response2 = httpclient.execute(httpget2); response2.close();
source share