Well, I need to make a java project that uses a urlConnection so I picked logging into a forum. I need to send an http post request to a site and then test to see if I'm logged in. This is a snippet of the code. This piece should login by sending the post data to Sign In but when it reads the html of the next page, it just prints out the login page so either I'm doing something wrong or it needs to log/send the cookies that the site sends. Any input would be greatly appreciated. Thanks.
final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded"; final String LOGIN_ACTION_NAME = "submit"; final String LOGIN_USER_NAME_PARAMETER_NAME = "username"; final String LOGIN_PASSWORD_PARAMETER_NAME = "password"; final String LOGIN_USER_NAME = "myusername"; final String LOGIN_PASSWORD = "mypassword"; String encodedLoginUserName = URLEncoder.encode(LOGIN_USER_NAME, "UTF-8"); String encodedLoginPassword = URLEncoder.encode(LOGIN_PASSWORD, "UTF-8"); //referer=http%3A%2F%2Fforum.tip.it%2Findex&username=myusername&password=mypassword&rememberMe=1 String content = "referer=http%3A%2F%2Fforum.tip.it%2Findex&" + LOGIN_USER_NAME_PARAMETER_NAME +"=" + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword + "&rememberMe=1"; System.out.println(content); // Send data URL url = new URL("http://forum.tip.it/index.php?app=core&module=global§ion=login"); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.setRequestMethod("POST"); httpcon.setDoOutput(true); httpcon.setDoInput(true); DataOutputStream wr = new DataOutputStream(httpcon.getOutputStream()); wr.writeBytes(content); wr.flush(); wr.close(); //write cookies? // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); httpcon.disconnect(); }