0

In my android project I'm uploading a zip file to a server using HTTP post request. In this case I'm using httpcore and httpmime libraries. I'm using an AsyncTask to make the upload. the doInBackground method of the AsyncTask is as below,

@Override
        protected String doInBackground(String... params) {

            try {
                String serverLoaction = params[0];
                String filePath = params[1];

                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(serverLoaction);

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody fileBody = new FileBody(new File(filePath));
                StringBody stringBody = new StringBody("data", ContentType.MULTIPART_FORM_DATA);

                builder.addPart("file", fileBody);
                builder.addPart("name", stringBody);

                httpPost.setEntity(builder.build());

                HttpResponse response = httpClient.execute(httpPost, localContext);

                BufferedReader reader = new BufferedReader(
                            new InputStreamReader(
                                    response.getEntity().getContent(), "UTF-8"));

                String sResponse = reader.readLine();
                return sResponse;

            } catch (Exception e) {
                if (dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;
            }

the code is compile and run well. but when upload task is carry on it does not upload the file and in the Log it shows below massage.

05-03 14:29:00.223 27471-27687/com.x.l D/dalvikvm: DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE
05-03 14:29:00.223 27471-27687/com.x.l W/dalvikvm: VFY: unable to resolve static field 44070 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser;
05-03 14:29:00.223 27471-27687/com.x.l D/dalvikvm: VFY: replacing opcode 0x62 at 0x001b
05-03 14:29:00.233 27471-27687/com.x.l D/dalvikvm: DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueFormatter;.INSTANCE
05-03 14:29:00.233 27471-27687/com.x.l W/dalvikvm: VFY: unable to resolve static field 44065 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueFormatter;
05-03 14:29:00.233 27471-27687/com.x.l D/dalvikvm: VFY: replacing opcode 0x62 at 0x0015

but it doesn't give any error. so i spent sum painful time trying to figure it out and i wasn't succeed.

the dependencies in my build.gradle file are as below,

dependencies {
    compile project(':volley')
    compile 'com.android.support:support-v4:22.2.1'
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.android.support:multidex:'
    compile 'org.apache.httpcomponents:httpcore:4.4.4'
    compile'org.apache.httpcomponents:httpmime:4.3.6'

}

Editted....... according to a stac answer I edited my code and added following two parts

String boundary = "-------------" + System.currentTimeMillis();

                httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + boundary);

and

builder.setBoundary(boundary);

so now my final code is like this.

@Override
    protected String doInBackground(String... params) {

        try {

            String serverLoaction = params[0];
            String filePath = params[1];

            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(serverLoaction);

            String boundary = "-------------" + System.currentTimeMillis();

            httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + boundary);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setBoundary(boundary);

            FileBody fileBody = new FileBody(new File(filePath));
            StringBody stringBody = new StringBody("data", ContentType.MULTIPART_FORM_DATA);

            builder.addPart("file", fileBody);
            builder.addPart("name", stringBody);

            httpPost.setEntity(builder.build());

            HttpResponse response = httpClient.execute(httpPost, localContext);

            BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));

            String sResponse = reader.readLine();
            return sResponse;

        } catch (Exception e) {
            if (dialog.isShowing())
                dialog.dismiss();
            Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
            return null;
        }
    }

so now it doesnt show that error I mentioned above. but still its not uploading the file. what's the wrong with my code. can someone suggest me possible fix for this issue. Thanks and regards!

Samantha Withanage
  • 3,811
  • 10
  • 30
  • 59

1 Answers1

0

I using volley library to upload file.
Hope this code can help you. This is class i using to request to server.

public class OnPostNewtRequest extends JsonRequest { MultipartEntityBuilder entity = MultipartEntityBuilder.create(); HttpEntity httpentity; private final Response.Listener mListener; private File mFilePart = null; private File mFileVideos = null; private final Map mStringPart;

public OnPostNewtRequest(String url, Response.ErrorListener errorListener,
                         Response.Listener<JSONObject> listener, File file,
                         File fileVideos, Map<String, String> mStringPart) {
    super(Method.POST, url, null, listener, errorListener);
    mListener = listener;
    mFilePart = file;
    mFileVideos = fileVideos;
    this.mStringPart = mStringPart;
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    buildMultipartEntity();
}

public void addStringBody(String param, String value) {
    mStringPart.put(param, value);
}

private void buildMultipartEntity() {
    if (mFileVideos != null)
        entity.addBinaryBody(Constant.KEY_FILE_VIDEO, mFileVideos, ContentType.create("video/mp4"), mFileVideos.getName());
    if (mFilePart != null)
        entity.addBinaryBody(Constant.KEY_FILE, mFilePart, ContentType.create("image/jpeg"), mFilePart.getName());
    for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
        try {
            entity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.defaultCharset()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

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

@Override
public byte[] getBody() {
    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<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));
    }
}

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

}


And How to using this request.
1 . First you using

Map params = new HashMap(); To add "key" and values to params example : params.put(Constant.KEY_WORD, mTag);.
Step 2 .

OnPostNewtRequest multipartRequest = new OnPostNewtRequest(Constant.URL_UP_POST, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (mAction != null) { mAction.onError(error); } dismiss(); error.printStackTrace(); } }, new Response.Listener() { @Override public void onResponse(JSONObject response) {

        }
    }, linkFileImage, fileVideos, params);

    YourApplication.getInstance().addToRequestQueue(multipartRequest);


Hope this help you.

Badman
  • 11
  • 2