2

场景 - 在帖子正文中上传二进制数据,处理包含 JSON 的响应正文。

如何使用 Volley 执行以下操作?

 curl -X  POST  -H "X-Application-Id: 3KxPB" -H "X-REST-API-Key: jkuI9"  -H "Content-Type: audio/3gp"  --data-binary '@test.3gp' https://host/1/files/audio

IMO - Volley 处理二进制 POST 正文类型存在差距,apache httpclient 在abstracthttpentity的子类中处理。如果由摄像头、麦克风或其他二进制输出传感器在手机上生成的缓冲二进制数据需要一种机制来包装并写入 POST 的主体,如何在 volley 中执行此操作?

我查看了PoolingByteArrayOutputStream并想做一些事情,比如填充缓冲区并获取 PBAOutStrm ,从缓冲区写入 PBAOutStrm ,然后将 OutStrm 翻转到 InputStream ,然后将其包装在 POST 请求的主体中,就像 ByteArrayEntity 一样。我看不出如何在凌空抽射中做到这一点。

4

2 回答 2

0

要发送二进制数据,您可以执行类似于我在此答案中所做的操作How to send a “multipart/form-data” POST in Android with Volley

于 2013-06-29T20:34:35.310 回答
0

我能够使用 Volley GsonRequest 解决这个问题:

public class MainActivity extends AppCompatActivity {


    String url = "https://arcane-anchorage-34204.herokuapp.com/handleCode";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        JSONObject jsonBody = null;
        try {
            jsonBody = new JSONObject ("{\"code\":\"NZ4UBUB\"}");
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "Error e = " + e, Toast.LENGTH_SHORT).show();
        }

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");

        RequestQueue queue = Volley.newRequestQueue(this);

        GsonRequest<Routine[]> gsonRequest = new GsonRequest<Routine[]>(Request.Method.POST, url, Routine[].class, headers, new Response.Listener<Routine[]>() {
            @Override
            public void onResponse(Routine[] routineData) {
                TextView serverData = (TextView)findViewById(R.id.serverData);

                String complete = "";
                String repeat = "";
                String hold = "";
                String perform = "";
                String txtData = "";

                for (int i = 0; i < routineData.length; i++) {
                    complete = (routineData[i].instructions.complete != null) ? "Complete: " + routineData[i].instructions.complete : "";
                    repeat = (routineData[i].instructions.repeat != null) ? "Repeat: " + routineData[i].instructions.repeat : "";
                    hold = (routineData[i].instructions.hold != null) ? "Hold: " + routineData[i].instructions.hold : "";
                    perform = (routineData[i].instructions.perform != null) ? "Perform: " + routineData[i].instructions.perform : "";

                    txtData += "DESCRIPTION: " + routineData[i].description[0] + ": " + routineData[i].description[1] + ", " + complete  + ", " + repeat  + ", " + hold  + ", " + perform + " ";
                }
                serverData.setText("Response: " + txtData);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                TextView serverData = (TextView)findViewById(R.id.serverData);

                serverData.setText("Response: " + volleyError.toString());

            }
        }, jsonBody);
        queue.add(gsonRequest);
    }
    public class GsonRequest<T> extends Request<T> {
        private final Gson gson = new Gson();
        private final Class<T> clazz;
        private final Map<String, String> headers;
        private final Response.Listener<T> listener;
        private JSONObject parameters = null;

        /**
         * Make a GET request and return a parsed object from JSON.
         *
         * @param url URL of the request to make
         * @param clazz Relevant class object, for Gson's reflection
         * @param headers Map of request headers
         */
        public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
                           Response.Listener<T> listener, Response.ErrorListener errorListener) {
            super(method, url, errorListener);
            this.clazz = clazz;
            this.headers = headers;
            this.listener = listener;
        }

        public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
                           Response.Listener<T> listener, Response.ErrorListener errorListener, JSONObject parameters) {
            this(method, url, clazz, headers, listener, errorListener);
            this.parameters = parameters;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return headers != null ? headers : super.getHeaders();
        }

        @Override
        public String getBodyContentType() {
            return "application/json";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return parameters.toString().getBytes(getParamsEncoding());
            } catch (UnsupportedEncodingException e) {
            }
            return null;
        }

        @Override
        protected void deliverResponse(T response) {
            listener.onResponse(response);
        }

        @Override
        protected Response<T> parseNetworkResponse(NetworkResponse response) {
            try {
                String json = new String(
                        response.data, HttpHeaderParser.parseCharset(response.headers));
                Log.i("RESPONSE", json);
                return Response.success(
                        gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JsonSyntaxException e) {
                return Response.error(new ParseError(e));
            }
        }
      }
    }
于 2017-02-26T19:48:58.130 回答