0

I have a thread here on stack overflow, and I already solved my problem upon using a multipart post through Volley. The problem is, what I have done is a String request and I want it to be change to JSONObject request because I needed to catch the server's response.

UPADATE : I also tried to change all Response<String> to Response<JSONObject>

This is my new implementation at my parseNetworkResponse(NetworkResponse response) method :

 @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response)
    {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

But unfortunately, It started calling the error response method

   @Override
   public void onErrorResponse(VolleyError error) {
                            Log.i("Error",error.toString());
                        }    

The error displayed is :

com.android.volley.ParseError: org.json.JSONException: Value <div of type java.lang.String cannot be converted to JSONObject                
Community
  • 1
  • 1
Earwin delos Santos
  • 2,965
  • 7
  • 20
  • 29

1 Answers1

0

As my answer in your previous question, I suggest that you create a custom request that reponses NetworkResponse or JSONObject like the following :

MultipartRequest.java:

class MultipartRequest extends Request<NetworkResponse> {
    private final Response.Listener<NetworkResponse> mListener;
    private final Response.ErrorListener mErrorListener;
    private final Map<String, String> mHeaders;
    private final String mMimeType;
    private final byte[] mMultipartBody;

    public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        this.mListener = listener;
        this.mErrorListener = errorListener;
        this.mHeaders = headers;
        this.mMimeType = mimeType;
        this.mMultipartBody = multipartBody;
    }

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

    @Override
    public String getBodyContentType() {
        return mMimeType;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        return mMultipartBody;
    }

    @Override
    protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
        try {
            return Response.success(
                    response,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (Exception e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(NetworkResponse response) {
        mListener.onResponse(response);
    }

    @Override
    public void deliverError(VolleyError error) {
        mErrorListener.onErrorResponse(error);
    }
}

Here, you can create a custom MultipartRequest extends Request<JSONObject> Hope this helps!

UPDATE FOR YOUR COMMENT:

I have a multipart entity is already included in apache http component libraries. Is there is any alternatives?

Here is my Request with HttpEntity and return a JSONArray. I think you can customize to return a JSONObject if you like.

private void makeJsonArrayRequest(Context context, int method, String url, HttpEntity httpEntity, final VolleyResponseListener listener) {
        JSONObject jsonRequest = null;
        String stringEntity;
        try {
            stringEntity = EntityUtils.toString(httpEntity);
            if (stringEntity != null) {
                jsonRequest = new JSONObject(stringEntity);
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                listener.onResponse(jsonArray);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(getErrorMessage(error));
            }
        }) {
            @Override
            protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
                ...
            }

            @Override
            protected VolleyError parseNetworkError(VolleyError volleyError) {
                ...
            }
        };

        // Access the RequestQueue through singleton class.
        MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
    }
BNK
  • 23,994
  • 8
  • 77
  • 87
  • the code is too long. I have a multipart entity is already included in apache http component libraries. Is there is any alternatives? – Earwin delos Santos Sep 02 '15 at 07:43
  • @EarwindelosSantos: see my updated answer. However, I suggest you use the code without using HttpEntity because of its deprecation. Long code is not a very big problem :) – BNK Sep 02 '15 at 07:50
  • i tried to edit all `Response` to `Response` but It start calling the error response method. this is the error `com.android.volley.ParseError: org.json.JSONException: Value
    – Earwin delos Santos Sep 02 '15 at 07:59
  • I also change my implement at `parseNetworkResponse(NetworkResponse response)` this is my new implementation `try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); }` – Earwin delos Santos Sep 02 '15 at 08:00
  • @EarwindelosSantos: are you sure the response is a valid JSONObject? Try `parseNetworkResponse` and post your debug values and/or logcat for more information – BNK Sep 02 '15 at 08:04
  • @EarwindelosSantos: refer to [this document for JSONObject](http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29) `source - A string beginning with { (left brace) and ending with } (right brace).` – BNK Sep 02 '15 at 08:10
  • the response is a valid json. I tried it on jsonlint.com I think there must be something wrong in my code – Earwin delos Santos Sep 02 '15 at 08:19
  • @EarwindelosSantos: check if in your response has `
    – BNK Sep 02 '15 at 08:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/88554/discussion-between-earwin-delos-santos-and-bnk). – Earwin delos Santos Sep 02 '15 at 08:34
  • do I need to override the getParams() method? – Earwin delos Santos Sep 02 '15 at 08:46
  • I already got my response when uploading an image file, but when the server side code checks the file type of the uploaded image, its not `image/jpg` type. the result was `application/octet-stream` type – Earwin delos Santos Sep 02 '15 at 09:18
  • 1
    For this content type, refer to my answer at the third link in your previous question. "ContentType contentType = ContentType.create("image/png");". Then you can replace png by jpeg or jpg if you like. – BNK Sep 02 '15 at 09:26
  • something weird happened, not all images or video from my mobile phone is being uploaded. there are few selected images and video are able to saved in the server – Earwin delos Santos Sep 02 '15 at 10:20
  • Volley is not recommended for large size files or upload too many files – BNK Sep 02 '15 at 10:31
  • im not uploading all at once. if that's the case, what you should I do? what alternatives do you have? please reply at the chat. – Earwin delos Santos Sep 02 '15 at 10:34
  • Retrofit, OkHttp or HttpUrlConnection...you can try. Sorry, I on holiday with family, cannot chat now – BNK Sep 02 '15 at 10:36
  • thank you very much, I think i really should switch http framework. – Earwin delos Santos Sep 02 '15 at 10:39