【问题标题】:Android: uploading photo using httpPostAndroid:使用 httpPost 上传照片
【发布时间】:2016-02-29 08:53:13
【问题描述】:

我在这里遇到一个问题:在 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 jars。好吧,这是我的 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
}

}

【问题讨论】:

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


    【解决方案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();
    

    然后处理收到的响应。

    【讨论】:

      【解决方案2】:

      从您的项目中删除库 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'
      }
      

      【讨论】:

      • 你的意思是,删除 jar 库文件?
      • 是删除jar库文件。
      • 我收到这些错误:无法解决:org.apache.httpcomponents:httpmime:4.3.6 无法解决:org.apache.httpcomponents:httpclient-android:4.3.5 我应该使用某个图书馆?
      • 不,不需要使用其他库,我正在这样做并且没有任何错误。如果可能的话,发布你的 gradle 文件。
      • @erickles 让你的 gradle 文件变成这样。
      猜你喜欢
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 2014-04-04
      • 2011-06-14
      • 2012-01-25
      • 1970-01-01
      • 2014-12-10
      • 2010-11-13
      相关资源
      最近更新 更多