2015-09-15 71 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();