Android Studio中MultiPartEntityBuilder错误(Android St

2019-10-23 18:03发布

我目前将某个应用得到相机和图库中的图片上传到PHP服务器。 但有什么毛病我的应用程序。 我用两种方法来完成这个任务。 第一种是将图像与Base64编码,然后在httppost使用UrlEncodedFormEntity。 有效。 然后我用的MultiPartEntityBuilder。 当我按下上传按钮,应用程序停止。 有人可以帮我吗? 我的代码如下,这是一个有点凌乱。 对于那个很抱歉。

package com.ascc.cloud;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;




import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {

Button btpic, btnup, btgal;
private Uri fileUri;
String picturePath=null;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "http://139.78.78.187/store.php";
public static int RESULT_LOAD_IMG=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btpic = (Button) findViewById(R.id.cpic);
    btpic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            clickpic();
        }
    });

    btnup = (Button) findViewById(R.id.up);
    btnup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            upload();
        }
    });

    btgal=(Button) findViewById(R.id.gallery);
    btgal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pickpic();
        }
    });

}

private void upload() {
    // Image location URL
    Log.e("path", "----------------" + picturePath);

    // Image
    Bitmap bm = BitmapFactory.decodeFile(picturePath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte[] ba = bao.toByteArray();
    ba1 =Base64.encodeToString(ba, Base64.DEFAULT);

    Log.e("base64", "-----" + ba1);

    // Upload image to server
    new uploadToServer().execute();

}

private void clickpic() {
    // Check Camera
    if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // Open default camera
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, 100);

    } else {
        Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
    }
}

private void pickpic(){
    //Choose from the gallery
    // Create intent to Open Image applications like Gallery, Google Photos
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG);


}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 100 && resultCode == RESULT_OK) {

        selectedImage = data.getData();
        photo = (Bitmap) data.getExtras().get("data");

        // Cursor to get image uri to display

        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap photo = (Bitmap) data.getExtras().get("data");
        ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
        imageView.setImageBitmap(photo);
    }

    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
            && null != data) {
        // Get the Image from data

        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        // Get the cursor
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        // Move to first row
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imgView = (ImageView) findViewById(R.id.Imageprev);
        // Set the Image in ImageView after decoding the String
        imgView.setImageBitmap(BitmapFactory
                .decodeFile( picturePath));
    }

}

public class uploadToServer extends AsyncTask<Void, Void, String> {

    private ProgressDialog pd = new ProgressDialog(MainActivity.this);
    protected void onPreExecute() {
        super.onPreExecute();
        pd.setMessage("Wait image uploading!");
        pd.show();
    }

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

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("image", ba1));
        nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);


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

             File file = new File(picturePath);
              Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
              Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
              mpEntity.addPart("image", new FileBody(file));

                    HttpEntity entity = mpEntity.build();
                httppost.setEntity(entity);
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);



        } catch (Exception e) {
            Log.v("log_tag", "Error in http connection " + e.toString());
        }
        return "Success";

    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        pd.hide();
        pd.dismiss();
     }
  }
 }

Answer 1:

在您的应用程序gradle这个,添加这些依赖关系:

dependencies {

    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'
    }

}

此外,添加以下封装选项:

android {
    ...

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
    }
}


Answer 2:

尝试经过大量的答案,我总结以下直接的解决方案,希望这将有助于一些你MultipartEntityBuilder在Android Studio中摇篮配置整合。 这是工作的魅力与API版本23。

编辑模块级buid.gradle文件如下:

android {
    ...
    packagingOptions {
         exclude 'META-INF/DEPENDENCIES'
         exclude 'META-INF/NOTICE'
         exclude 'META-INF/LICENSE'
         exclude 'META-INF/LICENSE.txt'
         exclude 'META-INF/NOTICE.txt'
    }
}

dependencies {
    ...
    compile "org.apache.httpcomponents:httpcore:4.4.1"
    compile "org.apache.httpcomponents:httpmime:4.3.6" 
}


文章来源: Android Studio MultiPartEntityBuilder Error