0

I need to login to an IIS web-server.

After login, I need to send an HTTP Post with a lot of data.

However, I don't know how to save my cookies from login and reuse them for subsequent HTTP calls.

My code

private final static Logger logger = Logger.getLogger(HttpURLConnectionExample.class);

private static final String CERTIFICATE_CLIENT = "/src/main/resources/clientcert.jks";
private static final String JAVAX_NET_SSL_KEY_STORE_PASSWORD = "javax.net.ssl.keyStorePassword";
private static final String JAVAX_NET_SSL_KEY_STORE = "javax.net.ssl.keyStore";
private static PropertiesManagement management;
private static final String LOGIN_PAGE = "https://alloggiatiweb.poliziadistato.it/Alloggiatiweb/Login.aspx";
private static final String COOKIES_HEADER = "Set-Cookie";
private static CookieManager msCookieManager = new CookieManager();
private static final String INTERNAL_PAGE = "https://alloggiatiweb.poliziadistato.it/Alloggiatiweb/Analisi.aspx";
private HttpsURLConnection conn;

private static void setCertificateSSL() throws FileNotFoundException, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    FileInputStream fin = new FileInputStream(management.getFilePath());
    KeyStore ks = KeyStore.getInstance(management.getSSLProtocol());
    ks.load(fin, management.getPassword().toCharArray());
    System.setProperty(JAVAX_NET_SSL_KEY_STORE, CERTIFICATE_CLIENT);
    System.setProperty(JAVAX_NET_SSL_KEY_STORE_PASSWORD, management.getPassword());
}

public static void main(String[] args) throws Exception {
    management = new PropertiesManagement();
    setCertificateSSL();
    HttpURLConnectionExample http = new HttpURLConnectionExample();
    http.login();
}

private void getInternalPage() throws Exception {
    URL obj = new URL(INTERNAL_PAGE);
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.connect();
    logger.info("[GET ON " + obj + " RESPONSE CODE-MESSAGE]" + conn.getResponseCode() + " - " + conn.getResponseMessage());
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    logger.info(response.toString());
}

private void login() throws Exception {
    URL obj = new URL(LOGIN_PAGE);
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("txtUtente", management.getUsername()));
    params.add(new BasicNameValuePair("txtPwd", management.getPassword()));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();
    conn.connect();
    Map<String, List<String>> headerFields = conn.getHeaderFields();
    List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
    if (cookiesHeader != null) {
        for (String cookie : cookiesHeader) {
            msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
        }
    }
    logger.info("[POST ON " + obj + " RESPONSE CODE-MESSAGE]" + conn.getResponseCode() + " - " + conn.getResponseMessage());
    getInternalPage();
    conn.disconnect();
}

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (NameValuePair pair : params) {
        if (first)
            first = false;
        else
            result.append("&");
        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }
    return result.toString();
}

and this is response

 INFO (HttpURLConnectionExample.java:125) [19 apr 2016 15:08:51,013] - [POST ON https://alloggiatiweb.poliziadistato.it/Alloggiatiweb/Login.aspx RESPONSE CODE-MESSAGE]200 - OK
 INFO (HttpURLConnectionExample.java:83) [19 apr 2016 15:08:51,461] - [GET ON https://alloggiatiweb.poliziadistato.it/Alloggiatiweb/Analisi.aspx RESPONSE CODE-MESSAGE]200 - OK
 INFO (HttpURLConnectionExample.java:94) [19 apr 2016 15:08:51,464] - <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transit
.....

but the page print aren't internal page but it's login page

Zaknafein
  • 398
  • 1
  • 3
  • 16
  • Hello! I have cleaned up your post a little bit. Your question is quite difficult to answer right now because it isn't obvious what you are attempting to ask. You need to clarify why you can't get the cookie data and why you can't post more information. For example, do you get an error message? If so, you need to post that with your question. – Knossos Apr 19 '16 at 08:56
  • i have edit, i hope now it's more clear! – Zaknafein Apr 19 '16 at 09:13
  • 302 indicates an HTTP redirection. You need to send another HTTP call to the URL indicated in the `location` header. – Knossos Apr 19 '16 at 09:16
  • infact i try to connect to another page (site/private.aspx), or i don't understand what you mean... – Zaknafein Apr 19 '16 at 09:20
  • You are sending your request to `https://alloggiatiweb.poliziadistato.it/Alloggiatiweb/Analisi.aspx` according to your log. Which results in a 302 that your server wants you to redirect to. – Knossos Apr 19 '16 at 09:22
  • And it's correct, i want to send a GET to that's page, but server answer me "redirect to login". I suppose that's why i can't login at the server... but in the previous method i send a post e server response 200... i don't understand... – Zaknafein Apr 19 '16 at 09:28
  • When I check that page in my browser, it complains about a missing certificate. You will likely need to use a valid certificate in your code to be able to access their server. – Knossos Apr 19 '16 at 09:32
  • i use a valid certificate, in browser and in my code. I edit the main page with the code from import and use certificate!!! – Zaknafein Apr 19 '16 at 09:34
  • Are you saving cookies for future use? Since you are using basic `HttpsURLConnection` it will not handle that for you. You need to take the cookies header you receive from your login call, and send those with your subsequent calls. – Knossos Apr 19 '16 at 09:46
  • Tha's problem...i don't know how to save cookie :D – Zaknafein Apr 19 '16 at 09:48
  • 1
    In that case, you would probably be better served by searching the Stack Overflow already answered database: [this would probably work for you](http://stackoverflow.com/a/16171708/503508) – Knossos Apr 19 '16 at 09:57
  • thanks, I'll try that solution... I used wrong keywords in the previous searching :-) – Zaknafein Apr 19 '16 at 10:00
  • doesn't work for me, I'm confused... P.S. cookiesHeader is empty.... – Zaknafein Apr 19 '16 at 13:16

0 Answers0