Post multipart request with Android SDK

前端 未结 12 2039
余生分开走
余生分开走 2020-11-22 04:38

I\'m trying to do something I thought would be relatively simple: Upload an image to a server with the Android SDK. I\'m found a lot of example code:

http://groups.g

12条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 05:27

    Here is a Simple approach if you are using the AOSP library Volley.

    Extend the class Request as follows-

    public class MultipartRequest extends Request {
        private static final String FILE_PART_NAME = "file";
        private final Response.Listener mListener;
        private final Map mFilePart;
        private final Map mStringPart;
        MultipartEntityBuilder entity = MultipartEntityBuilder.create();
        HttpEntity httpentity;
    
        public MultipartRequest(String url, Response.ErrorListener errorListener,
                                Response.Listener listener, Map file,
                                Map mStringPart) {
            super(Method.POST, url, errorListener);
            mListener = listener;
            mFilePart = file;
            this.mStringPart = mStringPart;
            entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            buildMultipartEntity();
        }
    
        public void addStringBody(String param, String value) {
            mStringPart.put(param, value);
        }
    
        private void buildMultipartEntity() {
            for (Map.Entry entry : mFilePart.entrySet()) {
                // entity.addPart(entry.getKey(), new FileBody(entry.getValue(), ContentType.create("image/jpeg"), entry.getKey()));
                try {
                    entity.addBinaryBody(entry.getKey(), Utils.toByteArray(new FileInputStream(entry.getValue())), ContentType.create("image/jpeg"), entry.getKey() + ".JPG");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            for (Map.Entry entry : mStringPart.entrySet()) {
                if (entry.getKey() != null && entry.getValue() != null) {
                    entity.addTextBody(entry.getKey(), entry.getValue());
                }
            }
        }
    
        @Override
        public String getBodyContentType() {
            return httpentity.getContentType().getValue();
        }
    
        @Override
        public byte[] getBody() throws AuthFailureError {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                httpentity = entity.build();
                httpentity.writeTo(bos);
            } catch (IOException e) {
                VolleyLog.e("IOException writing to ByteArrayOutputStream");
            }
            return bos.toByteArray();
        }
    
        @Override
        protected Response parseNetworkResponse(NetworkResponse response) {
            Log.d("Response", new String(response.data));
            return Response.success(new String(response.data), getCacheEntry());
        }
    
        @Override
        protected void deliverResponse(String response) {
            mListener.onResponse(response);
        }
    }
    

    You can create and add a request like-

    Map params = new HashMap<>();
            params.put("name", name.getText().toString());
            params.put("email", email.getText().toString());
            params.put("user_id", appPreferences.getInt( Utils.PROPERTY_USER_ID, -1) + "");
            params.put("password", password.getText().toString());
            params.put("imageName", pictureName);
            Map files = new HashMap<>();
            files.put("photo", new File(Utils.LOCAL_RESOURCE_PATH + pictureName));
            MultipartRequest multipartRequest = new MultipartRequest(Utils.BASE_URL + "editprofile/" + appPreferences.getInt(Utils.PROPERTY_USER_ID, -1), new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    Log.d("Error: ", error.toString());
                    FugaDialog.showErrorDialog(ProfileActivity.this);
                }
            }, new Response.Listener() {
                @Override
                public void onResponse(String jsonResponse) {
                    JSONObject response = null;
                    try {
                        Log.d("jsonResponse: ", jsonResponse);
                        response = new JSONObject(jsonResponse);
    
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (response != null && response.has("statusmessage") && response.getBoolean("statusmessage")) {
                            updateLocalRecord();
    
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    FugaDialog.dismiss();
                }
    
            }, files, params);
            RequestQueue queue = Volley.newRequestQueue(this);
            queue.add(multipartRequest);
    

提交回复
热议问题