Android:使用httpPost上传照片

时间:2015-11-26 10:01:15

标签: android android-studio http-post image-uploading

我在这里面临一个问题:在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;

我认为这段代码不对(我从Stackoverflow的一个问题得到了这个)。我相信我使用的是错误的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$3.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$1.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$2.call(AsyncTask.java:292)
                                                                            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                            at android.os.AsyncTask$SerialExecutor$1.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
}

}

2 个答案:

答案 0 :(得分:1)

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();

然后处理收到的回复。

答案 1 :(得分:0)

从您的项目中移除lib httpcore-4.4.4.jar org.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'
}