Multipart Image Request with JSON params in Single Call using volley Framework

独自空忆成欢 提交于 2019-12-23 20:11:10

问题


I am sending multipart Post request in Volley along with the JSon params {as required by server } , but at server side null params are received .

In this request, I need to send Requested params in one part fist, and the image file in the next part .

Map<String, String> params = new HashMap<String, String>();
            params.put("appkey", Constants.REQUEST_API_KEY);
            params.put("LoginID",issueRequest.getUserName());
            params.put("device_id", issueRequest.getImei().toString());
            params.put("tokenID", AppSharedPreferance.getAppSharedPreferanceInstance(mContext).getToken(Constants.REQUEST_TOKEN, null));
            params.put("issueId", String.valueOf(mRequestIssueId));
            params.put("serverID", String.valueOf(mServerId));

        JSONObject requestObj = new JSONObject();
        requestObj.put("ISSUE_DATA_KEY", new JSONObject(params));

I am requesting like :

PhotoMultipartRequest<JSONObject> photoMultipartRequest=null;

        photoMultipartRequest=new PhotoMultipartRequest<JSONObject>(url, requestObj.toString(), new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(IssueRequest.TAG, "inside Error");
                VolleyLog.d(Constants.REQUEST_ERROR, "Error had occured " + error.getCause());
            }
        }, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
               Log.v(IssueRequest.TAG,"Responce -> Issue Attachments "+response);
                String status = null;
                int code=-1;
                try {
                     code = (int) response.getInt("error_code");
                    status = response.getString("response_string");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.v(IssueRequest.TAG, "code->" + code + "status->" + status + "Responce ->" + response.toString());

            }
        },
                new File(issue.getAttachmentPath().toString()));

        photoMultipartRequest.setRetryPolicy(new RetryPolicyClass());
        Log.v(TAG, "Issue data " + photoMultipartRequest.toString());
        AppController.getInstance().addToRequestQueue(photoMultipartRequest);

When i am printing the response object, it has null params .

{"response_string":"Invalid request.","error_code":"1","required_params":null}

My VolleyRequest Class :

public  class PhotoMultipartRequest<T> extends Request<T> {


private static final String FILE_PART_NAME = "file";
private static final String FILE_JSON_PART_NAME = "parms";

private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File mImageFile;
protected Map<String, String> headers;
protected String params;
protected static final String PROTOCOL_CHARSET = "utf-8";

public PhotoMultipartRequest(String url, ErrorListener errorListener, Listener<T> listener, File imageFile){
    super(Method.POST, url, errorListener);

    mListener = listener;
    mImageFile = imageFile;

    buildMultipartEntity();
}

public PhotoMultipartRequest(String url,String params, ErrorListener errorListener, Listener<T> listener, File imageFile){
    super(Method.POST, url, errorListener);

    mListener = listener;
    mImageFile = imageFile;
    this.params=params;

    try {
        buildMultipartEntity1();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }

    headers.put("Accept", "application/json");

    return headers;
}

private void buildMultipartEntity1() throws UnsupportedEncodingException {

    mBuilder.addPart(FILE_JSON_PART_NAME, new StringBody(params));

    mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));

}

private void buildMultipartEntity(){


    mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));

}

@Override
public String getBodyContentType(){
    String contentTypeHeader = mBuilder.build().getContentType().getValue();
    return contentTypeHeader;
}

@Override
public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        mBuilder.build().writeTo(bos);
    } catch (IOException e) {
        VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
    }

    return bos.toByteArray();
}

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

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

}

I cannot find any clue of what went wrong. So, can anyone help me to correct my request class?

来源:https://stackoverflow.com/questions/32119687/multipart-image-request-with-json-params-in-single-call-using-volley-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!