Subsequent HTTPS POST request in Java with cookies retained

后端 未结 3 1785
轮回少年
轮回少年 2020-12-20 09:03

I need to obtain the input stream to a HTTPS URL eg. https://baseurl.com/mypdfgenerated.php?param=somevalue. In order to access this URL I need to get through the login page

3条回答
  •  [愿得一人]
    2020-12-20 10:05

    Not sure which is the best way but what helped me achieve this is the CloseableHttpClient class which along with BasicCookieStore retains cookies for subsequent requests once logged in, 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 cookies = cookieStore.getCookies();
    response.close();
    
    HttpGet httpget2 = new HttpGet(url_to_get_after_login);
    CloseableHttpResponse response2 = httpclient.execute(httpget2);
    response2.close();
    

提交回复
热议问题