6

In httpPost we setEntity(new StringEntity). But I'm using volley right now. I'd like to use that setEntity method in volley. How can I do that?

I would like to use it with Twitter api like this;

HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-  urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
Padma Kumar
  • 19,893
  • 17
  • 73
  • 130
Can Uludağ
  • 705
  • 8
  • 14
  • probably in the set headers method, you have to override the Request object to do custom things in volley – CQM Apr 07 '14 at 18:16
  • Hi , I am trying to do the same , need to set StringEntity .could you plz help me on this .. how did you solve this. – Nibha Jain Aug 11 '16 at 05:56

1 Answers1

4

@Override getBodyContentType() and getBody() in your extended Request<T> class using something similar to the following:

@Override
public String getBodyContentType() {
    return entity.getContentType().getValue();
}

@Override
public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        entity.writeTo(outputStream);
    } catch (IOException e) {
        VolleyLog.e("IOException @ " + getClass().getSimpleName());
    }
    return outputStream.toByteArray();
}
Submersed
  • 8,810
  • 2
  • 30
  • 38
  • This answer helped me. However it is not complete. The entity can be a ByteArrayEntity. This link has a more complete sample: http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley – Ray Jul 24 '14 at 17:05