Subsequent POST HTTPS request in Java with cookies saved

I need to get the input stream at https url, for example. https://baseurl.com/mypdfgenerated.php?param=somevalue . To access this URL, I need to go through the login page (for example, https://baseurl.com/login.php ), providing the BODY parameters:

user_name, web_pwd and submit_login 

I assume that the only way to successfully access the first URL is through POST in /login.php, followed by saving the cookies, and then reusing the cookie-session identifier in the next GET request; if this is the right approach, then can someone share the solution with the right / recent libraries?

0
source share
3 answers

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(); 
+2
source

Sample code snippet from Java Examples

 try { System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); URL url = new URL("https://www.yourwebsite.com/"); // Some URL HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setFollowRedirects(true); String query = "UserID=" + URLEncoder.encode("username"); query += "&"; query += "password=" + URLEncoder.encode("password"); query += "&"; // open up the output stream of the connection DataOutputStream output = new DataOutputStream( connection.getOutputStream() ); // write out the data output.writeBytes( query ); }catch(Exception err){ err.printStackTrace(); } 

See Using Cookies

+1
source

You should use a library that processes cookies for you, such as Apache HTTPClient .

0
source

Source: https://habr.com/ru/post/1233536/


All Articles