我需要获取HTTPS URL的输入流,例如。 https://baseurl.com/mypdfgenerated.php?param=somevalue。为了访问此URL,我需要通过提供BODY参数来浏览登录页面(例如https://baseurl.com/login.php):
user_name, web_pwd and submit_login
我假设成功访问第一个URL的唯一方法是通过POST到/login.php,然后存储cookie,然后在下一个GET请求中重用cookie-session-ID;如果这是正确的方法,那么有人可以与正确/最近的库共享解决方案吗?
答案 0 :(得分:2)
不确定哪种方法是最好的方法,但是帮助我实现这一目标的是CloseableHttpClient类,它与BasicCookieStore一起为登录后的请求保留了cookie,实现如下:
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();
答案 1 :(得分:1)
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();
}
答案 2 :(得分:0)
您应该使用为您处理Cookie的库,例如Apache HTTPClient。