The Drupal Version is 7 and the Services version is 3.4.

So, My login into Drupal goes like this:

  • Fetch a token. (POST)
  • Fetch a Cookie using the token. (POST)
  • Make GET Requests using DefaultHttpClient class to download data. (GET). This uses a token and cookie

This all works fine. But when I try to post my submissions to drupal server, look at the code below

 DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(submissionURL);            
  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SurveyReviewActivity.this);
        String id = prefs.getString("sessid", "FAIL");
        Log.e("SRA", id);
        String name = prefs.getString("sessname", "FAIL");
         Log.e("SRA", name);
         //String token_test = prefs.getString("token", "FAIL");
        //Log.e("SRA", token_test);

          httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
         httpPost.setHeader("X-CSRF-Token", X_CSRF_Token);
         // httpPost.setHeader("X-CSRF-Token", token_test);
         httpPost.setHeader("Cookie",name+"="+id);  try {
             httpPost.setEntity(new StringEntity(message, "UTF8"));
         } catch (UnsupportedEncodingException e) {
             Log.d("Encoding Exception",e.toString());

          try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
             if(httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == 401) {
                 Log.d("Submission failed ", httpResponse.getStatusLine().toString());


            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                String json = sb.toString();
                Log.d("Response", json);
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
        } catch (ClientProtocolException e) {

            Log.d("Protocol Exception",e.toString());
        } catch (IOException e) {

            Log.d("Protocol Exception",e.toString());

When I set the last header (the cookie header), I get a token invalid or CSRF Validation Failed Error to be specific. If I don not use a token the submission goes through, but submissions are shown as anonymous on the drupal CMS side. I thought that my shared preferences are crapping up my stored cookie, but they are not thats why I was verifying them by printing them to logcat. I can get a new cookie and even tried that, but its still the same error. Whats going on here? Here are my references to the previous posts I checked on various sites.

...so if you plan on giving a solution which says your shared preferences are giving you the wrong cookie back or your token is coming down with a new line....tried that all...not working. But its working great on the iOS side, the exact same logic and actions.Please also note that, my cookie was working in fetching the data (bolded that part on step 3), but not while uploading data, its giving me a CSRF validation failed or token failed error . Please help me out on this issue.....and yes for testing the current cookie lifetime is 2 years..

  • I think you're doing that slightly the wrong way round...you need to get the cookie before fetching the token, and pass it along in the request. There's a working php implementation here that describes the steps, should be easy enough to convert to java
    – Clive
    Jan 15 '14 at 19:00
  • but when i get a cookie, i parse it from json....I have to manually set a cookie unlike the browser....so i think it wont depend on the order...because the dowloads are working fine...only the uploads are giving me this trouble...thoughts?
    – Why-K-Rum
    Jan 15 '14 at 19:36
  • Hi, I have your same problem. I tried with HttpPost and HttpURLConnection, but I have solved nothing. Have you? If yes, could you kindly help me?
    – Grancein
    Dec 23 '16 at 14:25

CSRF token error comes when user is allready login to drupal site just logout then send the request you wont give this error again..hope this will help.


For what it's worth, this is only possible when using a HttpURLConnection in Android.

A code sample in this regard can be found at How to automate login a website – Java example.

    URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();

// Acts like a browser
conn.setRequestProperty("Host", "accounts.google.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
    conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://accounts.google.com/ServiceLoginAuth");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));


Not the answer you're looking for? Browse other questions tagged or ask your own question.