在Java中的后续HTTPS POST请求保留Cookie [英] Subsequent HTTPS POST request in Java with cookies retained

查看:820
本文介绍了在Java中的后续HTTPS POST请求保留Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取到HTTPS URL的输入流。 https://baseurl.com/mypdfgenerated.php?param=somevalue 。为了访问此网址,我需要访问登录页面(例如 https://baseurl.com/login。 php )通过提供BODY参数:

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 (eg. https://baseurl.com/login.php) by supplying BODY parameters:

user_name, web_pwd and submit_login 

我假设成功访问第一个URL的唯一方法是通过POST到/login.php,然后存储cookie,然后重用在下一个GET请求中的cookie会话ID;

I'm assuming the only way to successfully access the first URL is by a POST to the /login.php followed by storing the cookies and then reusing the cookie-session-ID in the next GET request; if this is the correct approach then could someone please share a solution with the correct/recent libraries?

推荐答案

示例代码片段来自

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();
}

查看 Cookie的使用

这篇关于在Java中的后续HTTPS POST请求保留Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆