执行Multipart上传图像时出现NoClassDefFoundError

时间:2016-06-29 14:07:40

标签: android noclassdeffounderror

我使用以下代码进行图片上传

package com.purpletab.warehouse.utils;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by macpurple8 on 15/06/16.
 */
public class MultipartRequest extends Request {
    private static final String KEY_PICTURE = "picture";
    private static final String KEY_FILE = "file";
    private static final String TAG = "MutlipartRequest";

    private HttpEntity mHttpEntity;
    private final Class mClass;
    private Response.Listener mListener;
    private Map mHeaders;
    private final Gson gson;

    public MultipartRequest(String url, File file, String imageName,
                            Class clazz,
                            Map headers,
                            Response.Listener listener,
                            Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        mHeaders = headers;
        mClass = clazz;
        mListener = listener;
        gson = new Gson();
        mHttpEntity = buildMultipartEntity(file, imageName);
    }

    public MultipartRequest(String url, String path, String imageName,
                            Class clazz,
                            Map headers,
                            Response.Listener listener,
                            Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        mHeaders = headers;
        mClass = clazz;
        mListener = listener;
        gson = new Gson();
        mHttpEntity = buildMultipartEntity(path, imageName);
    }

    private HttpEntity buildMultipartEntity(String path, String imageName) {
        File file = new File(path);
        return buildMultipartEntity(file, imageName);
    }

    private HttpEntity buildMultipartEntity(File file, String imageName) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        String fileName = file.getName();

        System.out.println("file name .. .. " + imageName);

        //builder.addBinaryBody(KEY_PICTURE, file, ContentType.create("image/jpeg"), imageName);
        builder.addBinaryBody(KEY_FILE, file, ContentType.create("image/jpeg"), imageName);
        return builder.build();
    }

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

    @Override
    public String getBodyContentType() {
        return mHttpEntity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            mHttpEntity.writeTo(bos);
        } catch (IOException e) {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        String json;
        try {
            json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, String.format("Encoding problem parsing API response. NetworkResponse:%s", response.toString()), e);
            return Response.error(new ParseError(e));
        }
        /*try {
            return Response.success(gson.fromJson(json, mClass), HttpHeaderParser.parseCacheHeaders(response));
        } catch (JsonSyntaxException e) {
            Log.e(TAG, String.format("Couldn't API parse JSON response. NetworkResponse:%s", response.toString()), e);
            Log.e(TAG, String.format("Couldn't API parse JSON response. Json dump: %s", json));
            return Response.error(new ParseError(e));
        }
*/
        Log.e(TAG, String.format("Couldn't API parse JSON response. Json dump: %s", json));

        return Response.success(response.toString(), HttpHeaderParser.parseCacheHeaders(response));

    }

    /**
     * Subclasses must implement this to perform delivery of the parsed
     * response to their listeners.  The given response is guaranteed to
     * be non-null; responses that fail to parse are not delivered.
     *
     * @param response The parsed response returned by
     *                 {@link #parseNetworkResponse(NetworkResponse)}
     */
    @Override
    protected void deliverResponse(Object response) {
        mListener.onResponse(response);
    }


    /**
     * Compares this object to the specified object to determine their relative
     * order.
     *
     * @param another the object to compare to this instance.
     * @return a negative integer if this instance is less than {@code another};
     * a positive integer if this instance is greater than
     * {@code another}; 0 if this instance has the same order as
     * {@code another}.
     * @throws ClassCastException if {@code another} cannot be converted into something
     *                            comparable to {@code this} instance.
     */
    @Override
    public int compareTo(Object another) {
        return 0;
    }
}

要触发方法,我调用以下代码

MultipartRequest request = new MultipartRequest(url, new File(imagepath), imageName,
                                    Response.class, null, new Response.Listener() {
                                @Override
                                public void onResponse(Object response) {
                                    System.out.println("Uploaded to server");

                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    System.out.println("Upload failed   " + error.getMessage());
                                }
                            });
                            request.setRetryPolicy(new DefaultRetryPolicy(
                                    AppConstants.SOCKET_TIMEOUT_MS,
                                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                            baseApp.addToRequestQueue(request, "a tag");

我得到的错误如下..

  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.purpletab.warehouse, PID: 14595
                                                                         java.lang.NoClassDefFoundError: org.apache.http.util.Args
                                                                             at org.apache.http.entity.mime.content.AbstractContentBody.<init>(AbstractContentBody.java:48)
                                                                             at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:96)
                                                                             at org.apache.http.entity.mime.MultipartEntityBuilder.addBinaryBody(MultipartEntityBuilder.java:141)
                                                                             at com.purpletab.warehouse.utils.MultipartRequest.buildMultipartEntity(MultipartRequest.java:76)
                                                                             at com.purpletab.warehouse.utils.MultipartRequest.<init>(MultipartRequest.java:48)
                                                                             at com.purpletab.warehouse.fragments.FormPageFragment$override.onClick(FormPageFragment.java:329)
                                                                             at com.purpletab.warehouse.fragments.FormPageFragment$override.access$dispatch(FormPageFragment.java)
                                                                             at com.purpletab.warehouse.fragments.FormPageFragment.onClick(FormPageFragment.java:0)
                                                                             at android.view.View.performClick(View.java:4438)
                                                                             at android.view.View$PerformClick.run(View.java:18431)
                                                                             at android.os.Handler.handleCallback(Handler.java:733)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:149)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5061)
                                                                             at java.lang.reflect.Method.invokeNative(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:515)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:603)
                                                                             at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

尝试添加此行:

useLibrary 'org.apache.http.legacy'

到app android文件中的build.gradle关闭。 这个apache.http pacakge在Android 6中已被弃用。