If you do not want to disable CSRF tokens, you will need to get the CSRF in one request, and then pass the extracted token along with the POST request.
// Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); // Get the CSRF token httpClient.execute(new HttpGet("http://www.yoursite.com/")); CookieStore cookieStore = httpClient.getCookieStore(); List <Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie: cookies) { if (cookie.getName().equals("XSRF-TOKEN")) { CSRFTOKEN = cookie.getValue(); } } // Access POST route using CSRFTOKEN HttpPost httppost = new HttpPost("http://www.yoursite.com/your-post-route"); try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("_token", CSRFTOKEN)); nameValuePairs.add(new BasicNameValuePair("stringdata", "Hello!")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block }
source share