This is my code:
public static String sendPostRequest(String url) {
StringBuffer sb = null;
try {
String data = URLEncoder.encode("user", "UTF-8") + "="
+ URLEncoder.encode("username", "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode("password", "UTF-8");
System.out.println(data); //Just to check if data is correct
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
DataOutputStream osw = new DataOutputStream(conn.getOutputStream());
osw.writeBytes(data);
osw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String in = "";
sb = new StringBuffer();
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
osw.close();
br.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
But whenever I try to log in through this http post request, it returns the html code which is always on that page of the site, not my specific html code that contains my user page. The html login form looks like this:
<td width="100" align="left"><span class="texte_listing_bold">Login:</span></td>
<td width="300" align="center"><input class="form_size1" type="text" name="user"></td>
</tr>
<tr>
<td width="100" align="left"><span class="texte_listing_bold">Password:</span></td>
<td width="300" align="center"><input class="form_size1" type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="login_action" value="true">
<input class="bouton_nosize" type="submit" value="Login">
</td>
Normally, the buttons have the name elements, and I can call those as well through my code, which does work and lets me log into such a site, but this won’t work for some reason. What’s the reason for this?
This login form uses a hidden input field called
login_actionwith valuetrue.You’ll need to pass that in your request along with username and password.
Simply make sure you have provided all required information.
You could check what the browser sends using a HTTP sniffer, but the best would be to look at the sources of the page you try to authenticate against.
If you don’t have access or control over the web server login page source then you probably shouldn’t be writing this code in the first place. The authentication mechanism can change in the future, and there may be many security restrictions against scripts such as the one you are tring to write, since it’s generally not accepted to allow bots to login to user pages and web-scrape content.