I am trying to send a HTTP/1.1 POST to http://uploaded.net/io/login, using HttpURLConnection
, in order to login to the website with my username and password.
For some reason it appears like byte[] postData
is not being sent to the server.
I receive the response code and message 200 OK, but the server replies with the JSON-formatted error message {"err":"Please type in id and password"} as if I never actually sent the data.
I've tried different methods (sending a String
, byte[]
etc., using different output writers) of sending the data but so far none of them have worked and I can't figure out where exactly it fails.
Here is the code snippet that I am working with:
package post;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
public class PostTest {
public static void login() throws MalformedURLException, IOException {
String urlParameters = String.format("id=%s&password=%s",
URLEncoder.encode(Config.getProperty("account.1.username"), "UTF-8"),
URLEncoder.encode(Config.getProperty("account.1.password"), "UTF-8")
);
byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
URL url = new URL(Config.getProperty("login.url"));
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setUseCaches(false);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
//prints: 26
System.out.println(postData.length);
//prints: id=test&password=123456789
System.out.println(urlParameters);
httpConn.getOutputStream().write(postData);
httpConn.getOutputStream().flush();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(httpConn.getInputStream()))) {
for (String line; (line = reader.readLine()) != null;)
System.out.println(line);
}
}
}
Live HTTP Headers (Firefox plugin) output:
POST /io/login HTTP/1.1
Host: uploaded.net
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/javascript, text/html, application/xml, text/xml, */*
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
X-Prototype-Version: 1.6.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://uploaded.net/
Content-Length: 20
Cookie: __utma=9[censored...]
Connection: keep-alive
id=test&pw=123456789
HTTP/1.1 200 OK
[...]
Edit: Added the Firefox' Live HTTP Headers output which I used to see what data is being sent through POST.
Is my assumption that byte[] postData
is not sent correctly, if at all, correct?
What changes do I have to make to get the login to work properly?