1đź‘Ť
Hey I was troubleshooting this same problem for a while now and I feel I need to share this. This is probably too late, but may be useful for all those in the future that need some help with a similar issue.
-
Request the login page and Django will set your cookie:
URL url = new URL("http://localhost:9999"); HttpURLConnection client = (HttpURLConnection) url.openConnection(); client.setDoInput(true); client.connect(); inputStream = client.getInputStream(); // open input stream //read input StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); String string = writer.toString(); //NOTE (look for this under this code section) String cookie= client.getHeaderField("Set-Cookie").get(0); client.disconnect();
NOTE: Your header values are stored in HashMap<String,List<String>>
, I used get(0)
because in my experience the list for the “Set-Cookie” only contains 1 value, so I get index 0 which in this example contains this:
"csrftoken=FwYSncufKaCZjxLWGUPq7ORZRvTXIxkU; expires=Sun, 09-Jul-2017 18:23:09 GMT; Max-Age=31449600; Path=/ 1"
As you can see it contains the csrf cookie.
Now you need to do two more things:
-
Put the previous cookie into your next url request properties
-
You need to put your csrf token value (in this example “FwYSncufKaCZjxLWGUPq7 ORZRvTXIxkU”, you can get this value with regex) into your POST parameters.
Here is some code to that:
url = new URL(LOGIN_URL);
client = (HttpURLConnection) url.openConnection();
client.setDoInput(true);
client.setDoOutput(true);
client.setRequestMethod("POST");
//set cookie to the previous cookie that has the correct csrf token
client.setRequestProperty("Cookie", cookie);
//set up the form params for the POST
String formParameters = "csrfmiddlewaretoken="
+ csrf + "&username="
+ "name" + "&password="
+ "pwd";
DataOutputStream wr = new DataOutputStream(
client.getOutputStream());
wr.write(formParameters.getBytes("UTF-8"));
wr.flush();
wr.close();
client.connect();
inputStream = client.getInputStream();
//read return input from the django server
writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
string = writer.toString();
Hope this helps for all those in the future!