I'm new to writing network code, and not very familiar with Java programming.
I'm trying to write a snippet to log into a website. I need to use http POST to submit the username and password.
I wrote a version using Apache http components and it worked fine, I could see there was a HTTP POST when monitoring the connection using Wireshark.
StringEntity loginForm = new StringEntity(postData);
HttpPost loginPost = new HttpPost(LOG_IN_URL);
loginPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
loginPost.setEntity(loginForm);
client.execute(loginPost);
The version above worked.
The postData
is
private static String getPostData(String checkCode) {
String postinfo1 = "operation=&usercode_text=myusername&userpwd_text=password&checkcode_text=";
String postinfo2 = "&submittype=%C8%B7+%C8%CF";
String postData = postinfo1 + checkCode + postinfo2;
return postData;
}
Then I wrote another one using HttpUrlConnection
URL logInUrl = new URL(LOG_IN_URL);
HttpURLConnection logConn = (HttpURLConnection) logInUrl.openConnection();
logConn.setDoOutput(true);
logConn.setRequestMethod("POST");
logConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
logConn.setChunkedStreamingMode(0);
OutputStream out = logConn.getOutputStream();
BufferedWriter logPost = new BufferedWriter(new OutputStreamWriter(out));
logPost.print(postData);
logPost.close();
After this block is executed, I can only see some TCP packages on Wireshark, but not a HTTP POST after them (as in the case with the Apache http components version), and I cannot log in to the website.
I am curious about the possible difference in the two versions of code the cause the latter to fail.
UPDATE I don't know why. But after I added
logConn.getResponseCode();
It works now. (Deleting this line it will fail). Can anyone explain why?