如何在Android Volley中使用setEntity?

6

在httpPost中,我们使用setEntity(new StringEntity)。但是我现在正在使用volley。我想在volley中使用该setEntity方法。我该怎么做呢?

我想像这样使用它与Twitter api;

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"));

可能在set headers方法中,您需要覆盖Request<T>对象以在Volley中执行自定义操作。 - CQM
嗨,我也在尝试做同样的事情,需要设置StringEntity。你能帮我吗?你是如何解决这个问题的? - Nibha Jain
1个回答

4

在你的扩展的 Request<T> 类中,使用类似以下内容的方法重写 getBodyContentType()getBody():

@Override

@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();
}

这个答案对我有帮助。不过它不是完整的。实体可以是一个ByteArrayEntity。这个链接有一个更完整的示例:https://dev59.com/EmQn5IYBdhLWcg3we3LD - Ray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接