Volley使用文件将字符串发送到服务器来解析Json对象

 收藏

这是我的Java代码:

 public void imageUpload(final Context context, final String imagePath) {
    final String requestBody;
    JSONObject jsonUser = null;
    JSONObject jsonAddress = null;
    JSONObject jsonDriver = null;
    JSONObject jsonImage = null;
    String URL = SIGN_UP;
    final String ConvertImage;

    jsonUser = new JSONObject();
    try {
        jsonUser.put("first_name", "ABC");
        jsonUser.put("last_name", "XYZ");
        jsonUser.put("email", "yash@gmail.com");
        jsonUser.put("phone", "9999900000");
        jsonUser.put("password", "Yash@123");

        jsonAddress = new JSONObject();
        jsonAddress.put("address", "MUMBAI");
        jsonAddress.put("city", "MUMBAI");
        jsonAddress.put("state", "MH");
        jsonAddress.put("zip", "369852");

        jsonDriver = new JSONObject();
        jsonDriver.put("middle_name", "GG");
        jsonDriver.put("vehicle_type", "CAR");
        jsonDriver.put("car_plate_number", "123456");
        jsonDriver.put("car_brand", "BMW");
        jsonDriver.put("making_year", "2011");
        jsonDriver.put("date_of_birth", "2019-06-01");
        jsonDriver.put("license_number", "12346579");
        jsonDriver.put("license_state", "MH");
        jsonDriver.put("social_security_number", "123456");

        JSONObject jsonObjectFinal = new JSONObject();
        jsonObjectFinal.put("user", jsonUser);
        jsonObjectFinal.put("address", jsonAddress);
        jsonObjectFinal.put("driver", jsonDriver);

    } catch (JSONException e) {
        e.printStackTrace();
    }


    SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("Response", response);
                    try {
                        JSONObject jObj = new JSONObject(response);
                        String message = jObj.getString("message");

                    } catch (JSONException e) {
                        // JSON error
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<String, String>();
            /*params.put("user", jsonUser + "");
            params.put("address", jsonAddress + "");
            params.put("driver", jsonDriver + "");
            Log.d("Param", "" + params + "***");*/
            return params;
        }
    };
    smr.addFile("license_image", imagePath);
    smr.addMultipartParam("user", "text/plain", jsonUser + "");
    smr.addMultipartParam("address", "text/plain", jsonAddress + "");
    smr.addMultipartParam("driver", "text/plain", jsonDriver + "");
    Log.d("Param", "" + smr.getMultipartParams() + "***");
    MySingleton.getInstance(context).addToRequestQueue(smr);
}

服务器显示:

data:-> 

[Object: null prototype] {
 address:
  '{"address":"SURAT","city":"SURAT","state":"GUJARAT","zip":"369852"}',
 driver:
  '{"middle_name":"GG","vehicle_type":"CAR","car_plate_number":"123456","car_brand":"BMW","making_year":"2011","date_of_birth":"2019-06-01","license_number":"12346579","license_state":"MH","social_security_number":"123456"}',
 user:
  '{"first_name":"YASH","last_name":"PANCHAL","email":"yash@gmail.com","phone":"8460277210","password":"Yash@123"}' }
files:-> [ { fieldname: 'license_image',
   originalname: '1559197608373.jpg',
   encoding: 'binary',
   mimetype: 'application/octet-stream',
   destination: 'C:\\Users\\Admin\\AppData\\Local\\Temp',
   filename: 'license_image-m6i0vcx0-1559197611770.octet-stream',
   path:
    'C:\\Users\\Admin\\AppData\\Local\\Temp\\license_image-m6i0vcx0-1559197611770.octet-stream',
   size: 53156 } ]

文件发送完美,但是JSON对象被解析为String,我想发送如下数据:

  {
user:{
'first_name': 'yash',
'last_name': 'panchal'
},
address:{
...
},
driver:{
...
},
licence_image: [file]
}

In Android I have to pass request in JSON object or array including files. If I try to parse the image via bitmap, the server returns undefined and if I try with pas as String it's working fine but when passing JSON data as above it results in sending object data as a single String.

回复
  • 风煜祺 回复

    看一下这个包含参数的多部分请求到特定服务器,并将其响应解析为json:

    private void saveProfileAccount() {
            // loading or check internet connection or something...
            // ... then
            String url = "http://www.angga-ari.com/api/something/awesome";
            VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
                @Override
                public void onResponse(NetworkResponse response) {
                    String resultResponse = new String(response.data);
                    try {
                        JSONObject result = new JSONObject(resultResponse);
                        String status = result.getString("status");
                        String message = result.getString("message");
    
                        if (status.equals(Constant.REQUEST_SUCCESS)) {
                            // tell everybody you have succed upload image and post strings
                            Log.i("Messsage", message);
                        } else {
                            Log.i("Unexpected", message);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    NetworkResponse networkResponse = error.networkResponse;
                    String errorMessage = "Unknown error";
                    if (networkResponse == null) {
                        if (error.getClass().equals(TimeoutError.class)) {
                            errorMessage = "Request timeout";
                        } else if (error.getClass().equals(NoConnectionError.class)) {
                            errorMessage = "Failed to connect server";
                        }
                    } else {
                        String result = new String(networkResponse.data);
                        try {
                            JSONObject response = new JSONObject(result);
                            String status = response.getString("status");
                            String message = response.getString("message");
    
                            Log.e("Error Status", status);
                            Log.e("Error Message", message);
    
                            if (networkResponse.statusCode == 404) {
                                errorMessage = "Resource not found";
                            } else if (networkResponse.statusCode == 401) {
                                errorMessage = message+" Please login again";
                            } else if (networkResponse.statusCode == 400) {
                                errorMessage = message+ " Check your inputs";
                            } else if (networkResponse.statusCode == 500) {
                                errorMessage = message+" Something is getting wrong";
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    Log.i("Error", errorMessage);
                    error.printStackTrace();
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<>();
                    params.put("api_token", "gh659gjhvdyudo973823tt9gvjf7i6ric75r76");
                    params.put("name", mNameInput.getText().toString());
                    params.put("location", mLocationInput.getText().toString());
                    params.put("about", mAvatarInput.getText().toString());
                    params.put("contact", mContactInput.getText().toString());
                    return params;
                }
    
                @Override
                protected Map<String, DataPart> getByteData() {
                    Map<String, DataPart> params = new HashMap<>();
                    // file name could found file base or direct access from real path
                    // for now just get bitmap data from ImageView
                    params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg"));
                    params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
    
                    return params;
                }
            };
    
            VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
        }