0
votes

I am currently working on an android app that will allow the user to upload images to my server. I am new to android development so currently facing issues with sending the file to the server while using the Http MultiPartEntity

Given below is the code I am using for uploading the file to the server private class UploadFileToServer extends AsyncTask {

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        //Change URL here
        String FILE_UPLOAD_URL = SERVER_SUBMIT_URL;

        try {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(FILE_UPLOAD_URL);
            MultipartEntity reqEntity = new MultipartEntity();

            File file1 = new File(filePath1);
            FileBody bin1 = new FileBody(file1);
            reqEntity.addPart("image1", bin1);

            //Extras
            reqEntity.addPart("command", new StringBody("uploadImages"));

            post.setEntity(reqEntity);
            HttpResponse response = client.execute(post);
            resEntity = response.getEntity();

            responseString = EntityUtils.toString(resEntity);

            return responseString;

        } catch (Exception e) {
            Log.v(TAG, e.toString());
            responseString = e.toString();
        }

        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {

        //Assuming JSON response From server
        // {"status": true, "ideaID" : 1}
        try{
            JSONObject json = new JSONObject(result);
            boolean status = json.getBoolean("status");
            if(status){
                showToast("Successfully Uploaded Images");

            }else{
                showToast("Image Uploading Failed");
            }

        }catch (Exception e) {
            showToast("Image Uploading Failed");
            Log.e(TAG, "Response from server: " + result + " " + e.getMessage());
        }
        // showing the server response in an alert dialog
        super.onPostExecute(result);
    }
}

I figured that the line "HttpResponse response = client.execute(post);" is where the app just crashed.

Here is the error that is shown in the log.

11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway /AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:838)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:  Caused by: java.lang.NoSuchFieldError: org.apache.http.message.BasicHeaderValueFormatter.INSTANCE
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.ContentType.toString(ContentType.java:153)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:53)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.mime.MultipartEntity.getEntity(MultipartEntity.java:119)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.entity.mime.MultipartEntity.isChunked(MultipartEntity.java:138)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.protocol.RequestContent.process(RequestContent.java:79)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.protocol.BasicHttpProcessor.process(BasicHttpProcessor.java:290)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.protocol.HttpRequestExecutor.preProcess(HttpRequestExecutor.java:167)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:413)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at com.example.grow.dubaiway.ImageActivity$UploadFileToServer.uploadFile(ImageActivity.java:197)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at com.example.grow.dubaiway.ImageActivity$UploadFileToServer.doInBackground(ImageActivity.java:156)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at com.example.grow.dubaiway.ImageActivity$UploadFileToServer.doInBackground(ImageActivity.java:137)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
11-22 00:24:41.341 8203-11792/com.example.grow.dubaiway E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:838) 

Could really use some help on the issue. Ive checked other posts but they didn't work for me.

Ive included the following libraries from the apache website. httpclient-4.5.1.jar httpclient-cache-4.5.1.jar httpcore-4.4.3.jar httpmime-4.5.1.jar

This is what my gradle file looks like apply plugin: 'com.android.application'

android {
   compileSdkVersion 23
   buildToolsVersion "23.0.2"

   defaultConfig {
       applicationId "com.example.neeraj.imageapp"
       minSdkVersion 14
       targetSdkVersion 23
       versionCode 1
       versionName "1.0"
   }
   buildTypes {
      release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       }
   }

   packagingOptions {
       exclude 'META-INF/DEPENDENCIES.txt'
       exclude 'META-INF/LICENSE.txt'
       exclude 'META-INF/NOTICE.txt'
       exclude 'META-INF/NOTICE'
       exclude 'META-INF/LICENSE'
       exclude 'META-INF/DEPENDENCIES'
       exclude 'META-INF/notice.txt'
       exclude 'META-INF/license.txt'
       exclude 'META-INF/dependencies.txt'
   }
}

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile 'com.android.support:appcompat-v7:23.1.1'
   compile 'com.android.support:design:23.1.1'
}

Any help would be appreciated. Thanks

1
HttpClient method is deprecated in coming version so why not using Volley or HttpURLConnection for making http requests - ρяσѕρєя K
@ρяσѕρєяK Volley uses Apache's library too :) - BNK
Hey guys, thanks for the feedback. Although, i fixed the problem by using older versions of the libraries. Switching to version 4.3.1 solved the problem for me, and now it works perfectly. Was able to use a multipart entity with a progress publisher as well. Thanks anyways. :) - neeraj

1 Answers

-1
votes

You can try using MultipartEntityBuilder

try
{
    File file1 = new File(filePath1);

    HttpClient client = new DefaultHttpClient();

    MultipartEntityBuilder entBuilder = MultipartEntityBuilder.create();
    entBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entBuilder.addBinaryBody(file1.getName(), file1);

    //Extras
    entBuilder.addPart("command", new StringBody("uploadImages"));

    /*
        If you need to send more files...

        entBuilder.addBinaryBody(file2.getName(), file2);
        entBuilder.addBinaryBody(file3.getName(), file3);
        ...
    */

    HttpEntity entity = entBuilder.build();
    HttpPost post = new HttpPost(FILE_UPLOAD_URL);
    post.setEntity(entity);

    HttpResponse response = client.execute(post);
    HttpEntity httpEntity = response.getEntity();

    return EntityUtils.toString(httpEntity);
}
catch(Exception e)
{
    e.printStackTrace();
}

You need to add dependencies in gradle

compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5'
compile (group: 'org.apache.httpcomponents' , name: 'httpmime' , version: '4.3.5') {
    exclude module: 'org.apache.httpcomponents:httpclient'
}

But I think that it would be better removing http apache dependencies (like HttpClient) from your code as Google removed it from Android 6 (api 23)

Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption