Mimi Itani
Mimi Itani

Reputation: 3

Upload image from android app to drupal using services

I am trying to upload an image from the android application to drupal. On drupal I have enabled the services module with rest server. My endpoint is androidrpc-endpoint. I have loged in successfully. However, now I am getting the error ( ["CSRF validation failed"] of type org.json.JSONArray cannot be converted to JSONObject). If anyone could point out the rror or give a me a tutorial to follow.

        String filePath = "mnt/sdcard/application/AboutUS.jpg";
        Bitmap bm = BitmapFactory.decodeFile(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] byteArrayImage = baos.toByteArray();
        String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
        HttpPost httpPost = new HttpPost("http://drupal/androidrpc-endpoint/file")
        JSONObject json = new JSONObject();
        JSONObject fileObject = new JSONObject();
        try {
            fileObject.put("file", encodedImage); 
            fileObject.put("filename", "AboutUS");
            fileObject.put("uid",1);
            fileObject.put("filepath", filePath);
            json.put("file", fileObject);

            StringEntity se = new StringEntity(json.toString());
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setEntity(se);
            //send the POST request
            HttpResponse response = httpclient.execute(httpPost);
            //read the response from Services endpoint
            String jsonResponse = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = new JSONObject(jsonResponse);//here is the error
            int fid;
            fid= jsonObject.getInt("fid");
            return null;
        }
        catch(Exception e){
            e.printStackTrace();
        }

Any help please

Upvotes: 0

Views: 832

Answers (1)

Emmanuel Buckshi
Emmanuel Buckshi

Reputation: 566

I am assuming you already know how to set the CSRF token for login authentication, since you mention that you have been logging in successfully. That said, upon logging in, you should receive a response which contains a new token. That is the token that you should be using for the subsequent request to your Services Endpoint.

Also, if you have session authentication enabled, you should be attaching your session information as well ("session_name=sessid")

Lastly, I don't see why you are unable to create a JSONObject with a String as its constructor parameter. Perhaps it might be useful to troubleshoot by creating your JSONObject as an empty object, and then using the .put() method to assign the String to a key, prior to using Logcat or debug to investigate its contents.

Upvotes: 1

Related Questions