2015-11-26 77 views
0

我在這裏面臨一個問題:在Android中使用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; 

我不認爲這個代碼是錯誤的(我在#1得到這個從一個問題在這裏)。我相信我正在使用錯誤的lib庫。好吧,這是我的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) 

我會aprecciate如果有人幫助我。

編輯 gradle這個build文件

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 
} 

}

回答

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

運行,然後用接收到的響應工作。

0

從您的項目中刪除庫的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' 
} 
+0

你的意思是,刪除jar庫文件? – erickles

+0

是刪除jar庫文件。 –

+0

我收到這些錯誤: 無法解析:org.apache.httpcomponents:httpmime:4.3.6 無法解析:org.apache.httpcomponents:HttpClient的-安卓4.3.5 我應該使用一些圖書館? – erickles