使用MultipartEntityBuilder和HttpURLConnection发送图像

时间:2017-02-15 21:13:27

标签: java android httpurlconnection apache-httpclient-4.x android-library

我正在尝试使用MultipartEntityBuilder和HttpURLConnection将图像发送到服务器,然后收到一个字符串答案(现在它使用http协议但是我将使用https使用此代码,或者非常类似的东西)。但是当我按下按钮发送它时,应用程序崩溃了,而logcat并没有告诉我有关捕获的任何信息。我所在的类的代码是下一个:

public class EnvioImagenes extends AsyncTask<String, Void, String>
{
    public String direccion="";
    public EnvioImagenes(String cuerpo){
        direccion=cuerpo;
    }


    protected String doInBackground(String... url){
        Bitmap bitmap = null;
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
        ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), direccion);
        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("Picture",contentPart);

        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url[0]).openConnection();
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            //Si quiero enviar/recibir una respuesta en el cuerpo del mensaje, tiene que estar lo siguiente:
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Connection", "Keep-Alive");
            String boundary= "--------------"+System.currentTimeMillis();
            multipartEntity.setBoundary(boundary);
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            DataOutputStream dos=new DataOutputStream(connection.getOutputStream());
            //connection.addRequestProperty(multipartEntity.getClass().getName(), multipartEntity.getClass().toString());
            //OutputStream output=new BufferedOutputStream(connection.getOutputStream());
            dos.writeBytes("\r\n");
            dos.flush();
            dos.close();
            //output.write(body.getBytes());
            //output.flush();

            int responseCode = connection.getResponseCode();
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder result = new StringBuilder();

            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }

            String responseString = result.toString();
            inputStream.close();
            connection.disconnect();
            return responseString;

        } catch(Exception exc) {
            String error = exc.toString();
            Log.e("This is the mistake.....", exc.getMessage());
            return error;
        }
    }
}

我下载了下载它的MultipartEntityBuilder库,如下链接所示:Android - MultipartEntity and dependencies。问题是,当build.gradle检查是否正常时,它会向我显示此警告:

Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.3 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages.

我试图解决它从浏览器下载软件包然后将其粘贴到库中的文件夹/ lib中,然后更改build.gradle中的代码以使程序从那里检查库,但随后我错了,我没有检测到我使用MultipartEntityBuilder的代码中的库;所以我认为问题在于代码本身:特别是因为我不使用httpClient。对于任何问题,build.gradle中的代码实际上就是这个:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"

    defaultConfig {
        applicationId "com.example.franco.pruebalogin"
        minSdkVersion 10
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:design:24.0.0'
    compile 'org.apache.httpcomponents:httpmime:4.5.3'
}

1 个答案:

答案 0 :(得分:0)

我走了那条路,但最终转向使用SyncHttpClient

private static final String COMPRESSED_FILE_PREFIX = "yourapp_image_compressed_";
private static final String JPEG_FILE_EXTENSION = ".jpeg";
private static final int FIVE_MINUTE_INIT_TIMEOUT = 300000;

public void uploadImage(Context applicationContext, ArrayList<String> filePathsToUpload) {
        RequestParams requestParams = new RequestParams();

        File imagesCacheDir;

        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            imagesCacheDir = new File(
                    android.os.Environment.getExternalStorageDirectory(),
                    "/Android/data/com.example.yourapp/UploadPics");
        } else {
            imagesCacheDir = applicationContext.getCacheDir();
        }

        if (!imagesCacheDir.exists()) {
            if (!imagesCacheDir.mkdirs()) {
                throw new RuntimeException("Image directory could not be created.");
            }
        }

        for (String filePath : filePathsToUpload) {
            File file;

            try {
                FileOutputStream out = new FileOutputStream(new File(imagesCacheDir,
                        COMPRESSED_FILE_PREFIX + filePathsToUpload.size() + 1 + JPEG_FILE_EXTENSION));

                BitmapFactory.decodeFile(filePath).compress(Bitmap.CompressFormat.JPEG, compress ? 90 : 100, out);

                file = new File(imagesCacheDir, COMPRESSED_FILE_PREFIX + filePathsToUpload.size() + 1 + JPEG_FILE_EXTENSION);
                requestParams.put(file.getName(), file);
                out.close();
            } catch (FileNotFoundException fnfe) {
                throw new RuntimeException("Image file not found.");
            } catch (IOException ie) {
                throw new RuntimeException("Error writing image to file.);
            }
        }

        SyncHttpClient client = new SyncHttpClient();
        client.setTimeout(FIVE_MINUTE_INIT_TIMEOUT);

        Map<String, String> headers = VolleyUtils.getBigOvenHeaders();
        headers.putAll(VolleyUtils.getAuthenticationHeader());

        for (String headerKey : headers.keySet()) {
            client.addHeader(headerKey, headers.get(headerKey));
        }

        MySSLSocketFactory socketFactory;

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            socketFactory = new MySSLSocketFactory(trustStore);
            socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            client.setSSLSocketFactory(socketFactory);
        } catch (Exception e) {
            // Probably should die or something, unless http is okay (if you need https, this is no go)
        }

        client.setTimeout(FIVE_MINUTE_INIT_TIMEOUT);

        client.post(this, "https://www.myapp.com/imageUploader", requestParams, new RotatingBitmapTextHttpResponseHandler(filePathsToUpload, notificationBuilder, onCompletionText));
}

您可以将HttpResponseHandler更改为您想要的任何内容。在这种情况下,我创建了一个跟踪进度的类,并在通知中显示它。你可以做任何你喜欢的事情。