2015-09-15 29 views
0

我需要获取到HTTPS URL的输入流例如。 https://baseurl.com/mypdfgenerated.php?param=somevalue。为了访问这个URL,我需要通过提供车身参数通过登录页面来获得(如https://baseurl.com/login.php):后续HTTPS POST请求在Java中与保留的Cookie

user_name, web_pwd and submit_login 

我假设成功访问第一个网址的唯一方法是通过一个POST到/login.php,然后存储cookie,然后在下一个GET请求中重复使用cookie会话ID;如果这是正确的方法,那么有人可以与正确的/最近的图书馆共享一个解决方案吗?

+1

传递一个[CookieManager](http://docs.oracle.com/jav ase/8/docs/api/java/net/CookieManager.html)复制到[CookieHandler.setDefault](http://docs.oracle.com/javase/8/docs/api/java/net/CookieHandler.html#setDefault -java.net.CookieHandler-)。 – VGR

回答

0

您应该使用一个为您处理cookies的库,如Apache HTTPClient。从Java Samples

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

1

示例代码段看一看Usage of cookies

+0

发现SE的更多解决方案:http://stackoverflow.com/questions/496651/connecting-to-remote-url-which-requires-authentication-using-java –

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