Android: 使用 httpPost 上传照片

Android: uploading photo using httpPost

我在这里遇到一个问题:在 Android 中使用 httpPost 上传照片。基本上,这就是我正在做的事情:

String result = "";
    boolean isOperationOk = false;
    File file;

    file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "USER_ID_" + String.valueOf(user.getId()) +  "_foto.jpg");

    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    try {

        file.createNewFile();
        FileOutputStream fo = new FileOutputStream(file);
        fo.write(user.getFoto());
        fo.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    //MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(context.getString(R.string.webservice));

    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);

    nameValuePair.add(new BasicNameValuePair("op", "photo-upload"));

    nameValuePair.add(new BasicNameValuePair("hash", context.getString(R.string.hash_webservice)));

    nameValuePair.add(new BasicNameValuePair("photo", file.getAbsolutePath()));

    nameValuePair.add(new BasicNameValuePair(User.TAGid, String.valueOf(user.getId())));

    for (int index = 0; index < nameValuePair.size(); index++) {

        if (nameValuePair.get(index).getName().equalsIgnoreCase("photo")) {
            // If the key equals to "image", we use FileBody to transfer the data
            multipartEntity.addPart(nameValuePair.get(index).getName(),
                    new FileBody(new File(nameValuePair.get(index).getValue())));
        } else {
            // Normal string data
            multipartEntity.addPart(nameValuePair.get(index).getName(),new StringBody(nameValuePair.get(index).getValue(), ContentType.TEXT_PLAIN));
        }
    }

    //httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    httpPost.setEntity(multipartEntity);

    HttpResponse response = httpClient.execute(httpPost);

    if (response.getStatusLine().getStatusCode() == 200)
    {
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
    }

    if(result != ""){
        JSONObject reader = new JSONObject(result);
        isOperationOk = reader.getBoolean("valid");
        this.message = reader.getString("message");
    }else
        isOperationOk = false;

    return isOperationOk;

我认为这段代码没有错(我是从 Whosebug 上的一个问题中得到的)。我相信我使用了错误的 lib jar。嗯,这是我的 build.gradle 文件(我正在使用 Android Studio):

android {

packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/dependencies.txt'

    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/notice.txt'

    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/license.txt'
}

compileSdkVersion 23
buildToolsVersion "23.0.1"
useLibrary 'org.apache.http.legacy'
defaultConfig {
    applicationId "br.com.app"
    minSdkVersion 11
    targetSdkVersion 23
    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:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services-gcm:8.3.0'
compile 'com.android.support:support-v4:23.1.1'
compile files ('libs/httpcore-4.4.4.jar')
compile files ('libs/org.apache.httpcomponents.httpclient_4.5.1.jar')

}

我使用了正确的库吗?因为这是我尝试上传照片时得到的结果:

11-26 07:49:37.377 32565-32726/br.com.app E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
                                                                        Process: br.com.app, PID: 32565
                                                                        java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                            at android.os.AsyncTask.done(AsyncTask.java:304)
                                                                            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                            at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
                                                                            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                            at java.lang.Thread.run(Thread.java:818)
                                                                         Caused by: java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/message/BasicHeaderValueFormatter; in class Lorg/apache/http/message/BasicHeaderValueFormatter; or its superclasses (declaration of 'org.apache.http.message.BasicHeaderValueFormatter' appears in /system/framework/ext.jar)
                                                                            at org.apache.http.entity.ContentType.toString(ContentType.java:153)
                                                                            at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:53)
                                                                            at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
                                                                            at org.apache.http.entity.mime.MultipartEntity.getEntity(MultipartEntity.java:119)
                                                                            at org.apache.http.entity.mime.MultipartEntity.isChunked(MultipartEntity.java:138)
                                                                            at org.apache.http.protocol.RequestContent.process(RequestContent.java:84)
                                                                            at org.apache.http.protocol.BasicHttpProcessor.process(BasicHttpProcessor.java:295)
                                                                            at org.apache.http.protocol.HttpRequestExecutor.preProcess(HttpRequestExecutor.java:165)
                                                                            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:427)
                                                                            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:580)
                                                                            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:503)
                                                                            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:481)
                                                                            at sync.HttpPostRecordTask.uploadPhoto(HttpPostRecordTask.java:348)
                                                                            at sync.HttpPostRecordTask.doInBackground(HttpPostRecordTask.java:145)
                                                                            at sync.HttpPostRecordTask.doInBackground(HttpPostRecordTask.java:42)
                                                                            at android.os.AsyncTask.call(AsyncTask.java:292)
                                                                            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                            at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231) 
                                                                            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                                            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                                            at java.lang.Thread.run(Thread.java:818)

如果有人帮助我,我将不胜感激。

编辑 gradle 构建文件

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

}

从您的项目中删除库 httpcore-4.4.4.jarorg.apache.httpcomponents.httpclient_4.5。 1.jar

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/dependencies.txt'

        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'

        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
    }

    defaultConfig {
        applicationId "com.dev.hb.testing"
        manifestPlaceholders = [manifestApplicationId: "${applicationId}"]
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile('org.apache.httpcomponents:httpmime:4.3.6') {
        exclude module: 'httpclient'
    }
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services-gcm:8.3.0'
    compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
}

DefaultHttpClient 已弃用,请像这样使用 url.openConnection()

List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("origin", origin.toString()));
nameValuePairs.add(new BasicNameValuePair("destination", destination.toString() ));
nameValuePairs.add(new BasicNameValuePair("sensor", "false"));
String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");

和 运行 在 AsyncTask

String response = "";
URL url = new URL(Config.URL_PREFIX + "?" + paramString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(Consts.CONNECT_TIMEOUT);
conn.setReadTimeout(Consts.READ_TIMEOUT);
//Send request
DataOutputStream wr = new DataOutputStream (
    conn.getOutputStream());
wr.flush();
wr.close();
//Get Response
InputStream is = conn.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
try {
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
response = sb.toString();
reader.close();

然后处理收到的响应。