【问题标题】:Send ByteArray with Android volley使用 Android 凌空发送 ByteArray
【发布时间】:2015-03-02 09:32:54
【问题描述】:

有没有办法用 Volley 发送字节数组?

现在我正在使用这个:

post.setEntity(new ByteArrayEntity(rawPacket.toByteArray()));
try {
    response = client.execute(post);
} catch (IOException e) {
    e.printStackTrace();
}

Volley 中有这样的东西吗?有一种方法可以通过自定义对象与 POST/GET 请求一起发送吗?

protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<>();
            params.put("RawPacket", rawPacket.toByteArray().toString());
            return params;
        }

我需要protected Map&lt;String, ByteArray&gt; getParams() 之类的东西

【问题讨论】:

    标签: android post bytearray android-volley


    【解决方案1】:

    我找到了覆盖函数public byte[] getBody() 以发送自定义数据的解决方案,我应该更好地阅读文档!

    StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://www.example.com/",
        new Response.Listener<String>() {
          @Override
          public void onResponse(String response) {
          }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
      }) {
      @Override
      public byte[] getBody() throws AuthFailureError {
        return new byte[] {1, 2, 3, 4, 5};
      }
    

    【讨论】:

    • 正是我想要的。你应该接受这个答案
    【解决方案2】:

    见下面的代码:

    public class JsonArrayRequest extends JsonRequest<JSONArray> {
    /**
     * Creates a new request.
     * @param url URL to fetch the JSON from
     * @param listener Listener to receive the JSON response
     * @param errorListener Error listener, or null to ignore errors.
     */
    public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
        super(Method.GET, url, null, listener, errorListener);
    }
    

    您必须创建 JsonRequest 的子类并使用它。

    查看相关链接: Volley - Sending a POST request using JSONArrayRequest

    还可能希望对字节进行 Base64 编码并将其添加到 JsonArray。

    【讨论】:

    • 是的,但是如何将自定义对象放入我发送的参数中?
    • 使用 JsonArray,您几乎可以在其中存储任何值
    • 如何构建带有 ByteArray 参数的 json?
    • 你为什么不把它Base64编码,然后调用使用把它放在JsonArray中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多