2

我試圖上傳使用多部分實體的視頻文件上傳視頻文件。對於使用多部分實體法,有人提到,我應該將以下jar文件的HttpClient,httpmime,的HttpCore。但在添加的HttpCore jar文件我不能運行我的項目,它拋出在我的控制檯下面error無法使用多部分實體

在去除這個特殊的罐子,當我嘗試運行我的應用我的日誌顯示以下error in my code

這裏是我的代碼,供大家參考:

public class UploadActivity extends Activity { 
// LogCat tag 
private static final String TAG = MainActivity.class.getSimpleName(); 

private ProgressBar progressBar; 
private String filePath = null; 
private TextView txtPercentage; 
private ImageView imgPreview; 
private VideoView vidPreview; 
private Button btnUpload; 
long totalSize = 0; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_upload); 
    txtPercentage = (TextView) findViewById(R.id.txtPercentage); 
    btnUpload = (Button) findViewById(R.id.btnUpload); 
    progressBar = (ProgressBar) findViewById(R.id.progressBar); 
    imgPreview = (ImageView) findViewById(R.id.imgPreview); 
    vidPreview = (VideoView) findViewById(R.id.videoPreview); 

    // Changing action bar background color 
    /* 
    * getActionBar().setBackgroundDrawable(new 
    * ColorDrawable(Color.parseColor(getResources().getString(
    * R.color.action_bar)))); 
    */ 

    // Receiving the data from previous activity 
    Intent i = getIntent(); 

    // image or video path that is captured in previous activity 
    filePath = i.getStringExtra("filePath"); 

    // boolean flag to identify the media type, image or video 
    boolean isImage = i.getBooleanExtra("isImage", true); 

    if (filePath != null) { 
     // Displaying the image or video on the screen 
     previewMedia(isImage); 
    } else { 
     Toast.makeText(getApplicationContext(), 
       "Sorry, file path is missing!", Toast.LENGTH_LONG).show(); 
    } 

    btnUpload.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // uploading the file to server 
      new UploadFileToServer().execute(); 
     } 
    }); 

} 

/** 
* Displaying captured image/video on the screen 
* */ 
private void previewMedia(boolean isImage) { 
    // Checking whether captured media is image or video 
    if (isImage) { 
     imgPreview.setVisibility(View.VISIBLE); 
     vidPreview.setVisibility(View.GONE); 
     // bimatp factory 
     BitmapFactory.Options options = new BitmapFactory.Options(); 

     // down sizing image as it throws OutOfMemory Exception for larger 
     // images 
     options.inSampleSize = 8; 

     final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); 

     imgPreview.setImageBitmap(bitmap); 
    } else { 
     imgPreview.setVisibility(View.GONE); 
     vidPreview.setVisibility(View.VISIBLE); 
     vidPreview.setVideoPath(filePath); 
     // start playing 
     vidPreview.start(); 
    } 
} 

/** 
* Uploading the file to server 
* */ 
private class UploadFileToServer extends AsyncTask<Void, Integer, String> { 
    @Override 
    protected void onPreExecute() { 
     // setting progress bar to zero 
     progressBar.setProgress(0); 
     super.onPreExecute(); 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) { 
     // Making progress bar visible 
     progressBar.setVisibility(View.VISIBLE); 

     // updating progress bar value 
     progressBar.setProgress(progress[0]); 

     // updating percentage value 
     txtPercentage.setText(String.valueOf(progress[0]) + "%"); 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
     return uploadFile(); 
    } 

    @SuppressWarnings("deprecation") 
    private String uploadFile() { 
     String responseString = null; 

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL); 

     try { 
      AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
        new ProgressListener() { 

         @Override 
         public void transferred(long num) { 
          publishProgress((int) ((num/(float) totalSize) * 100)); 
         } 
        }); 

      File sourceFile = new File(filePath); 

      // Adding file data to http body 
      entity.addPart("image", new FileBody(sourceFile)); 

      // Extra parameters if you want to pass to server 
      entity.addPart("website", 
        new StringBody("www.androidhive.info")); 
      entity.addPart("email", new StringBody("[email protected]")); 

      totalSize = entity.getContentLength(); 
      httppost.setEntity(entity); 

      // Making server call 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity r_entity = response.getEntity(); 

      int statusCode = response.getStatusLine().getStatusCode(); 
      if (statusCode == 200) { 
       // Server response 
       responseString = EntityUtils.toString(r_entity); 
      } else { 
       responseString = "Error occurred! Http Status Code: " 
         + statusCode; 
      } 

     } catch (ClientProtocolException e) { 
      responseString = e.toString(); 
     } catch (IOException e) { 
      responseString = e.toString(); 
     } 

     return responseString; 

    } 

    @Override 
    protected void onPostExecute(String result) { 
     Log.e(TAG, "Response from server: " + result); 

     // showing the server response in an alert dialog 
     showAlert(result); 

     super.onPostExecute(result); 
    } 

} 

/** 
* Method to show alert dialog 
* */ 
private void showAlert(String message) { 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setMessage(message).setTitle("Response from Servers") 
      .setCancelable(false) 
      .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        // do nothing 
       } 
      }); 
    AlertDialog alert = builder.create(); 
    alert.show(); 
} 

}

誰能幫我解決這個問題?就像爲什麼當我嘗試添加Httpcore jar時出現此錯誤,我該如何克服這些... ???

還是有,我做使它工作的任何備用????

+0

多地塞米松文件通常意味着它是與你的jar文件。檢查你的項目中是否有兩次使用同一個罐子? – San

+0

值得一提的是,使用[HttpClient](http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client)進行開發可能會導致您遇到問題未來。它已被棄用。 – Knossos

回答

1

下面的代碼測試和工程從Android的視頻上傳。

正如Knossos在您的問題的評論中所說的那樣,值得一提的是,儘管您可能需要檢查他們是否正確處理Multipart消息,但在Android中有更新推薦的HTTP庫。 HTTP的Android的一個很好的概述(其中有一個有趣的歷史)是在這裏:https://packetzoom.com/blog/which-android-http-library-to-use.html

import java.io.File; 
import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.mime.HttpMultipartMode; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

import android.os.AsyncTask; 
import android.util.Log; 

public class VideoUploadTask extends AsyncTask<String, String, Integer> { 
    /* This Class is an AsynchTask to upload a video to a server on a background thread 
    * 
    */ 

    private VideoUploadTaskListener thisTaskListener; 
    private String serverURL; 
    private String videoPath; 

    public VideoUploadTask(VideoUploadTaskListener ourListener) { 
     //Constructor 
     Log.d("VideoUploadTask","constructor"); 

     //Set the listener 
     thisTaskListener = ourListener; 
    } 

    @Override 
    protected Integer doInBackground(String... params) { 
     //Upload the video in the background 
     Log.d("VideoUploadTask","doInBackground"); 

     //Get the Server URL and the local video path from the parameters 
     if (params.length == 2) { 
      serverURL = params[0]; 
      videoPath = params[1]; 
     } else { 
      //One or all of the params are not present - log an error and return 
      Log.d("VideoUploadTask doInBackground","One or all of the params are not present"); 
      return -1; 
     } 


     //Create a new Multipart HTTP request to upload the video 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(serverURL); 

     //Create a Multipart entity and add the parts to it 
     try { 
      Log.d("VideoUploadTask doInBackground","Building the request for file: " + videoPath); 
      FileBody filebodyVideo = new FileBody(new File(videoPath)); 
      StringBody title = new StringBody("Filename:" + videoPath); 
      StringBody description = new StringBody("Test Video"); 
      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
      reqEntity.addPart("videoFile", filebodyVideo); 
      reqEntity.addPart("title", title); 
      reqEntity.addPart("description", description); 
      httppost.setEntity(reqEntity); 
     } catch (UnsupportedEncodingException e1) { 
      //Log the error 
      Log.d("VideoUploadTask doInBackground","UnsupportedEncodingException error when setting StringBody for title or description"); 
      e1.printStackTrace(); 
      return -1; 
     } 

     //Send the request to the server 
     HttpResponse serverResponse = null; 
     try { 
      Log.d("VideoUploadTask doInBackground","Sending the Request"); 
      serverResponse = httpclient.execute(httppost); 
     } catch (ClientProtocolException e) { 
      //Log the error 
      Log.d("VideoUploadTask doInBackground","ClientProtocolException"); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      //Log the error 
      Log.d("VideoUploadTask doInBackground","IOException"); 
      e.printStackTrace(); 
     } 

     //Check the response code 
     Log.d("VideoUploadTask doInBackground","Checking the response code"); 
     if (serverResponse != null) { 
      Log.d("VideoUploadTask doInBackground","ServerRespone" + serverResponse.getStatusLine()); 
      HttpEntity responseEntity = serverResponse.getEntity(); 
      if (responseEntity != null) { 
       //log the response code and consume the content 
       Log.d("VideoUploadTask doInBackground","responseEntity is not null"); 
       try { 
        responseEntity.consumeContent(); 
       } catch (IOException e) { 
        //Log the (further...) error... 
        Log.d("VideoUploadTask doInBackground","IOexception consuming content"); 
        e.printStackTrace(); 
       } 
      } 
     } else { 
      //Log that response code was null 
      Log.d("VideoUploadTask doInBackground","serverResponse = null"); 
      return -1; 
     } 

     //Shut down the connection manager 
     httpclient.getConnectionManager().shutdown(); 
     return 1; 
    } 

    @Override 
    protected void onPostExecute(Integer result) { 
     //Check the return code and update the listener 
     Log.d("VideoUploadTask onPostExecute","updating listener after execution"); 
     thisTaskListener.onUploadFinished(result); 
    } 

} 
+0

我收到此錯誤:「由:java.lang.NoClassDefFoundError:失敗的解決方案:Lorg/apache/http/util/Args;引起的錯誤」 在以下行中:「FileBody filebodyVideo = new FileBody(new File(videoPath));」 –

+0

好的 - 看起來您可能在訪問罐子時遇到問題。假設您使用Eclipse,請參閱此答案以瞭解最佳方式:http://stackoverflow.com/a/27906193/334402 – Mick

+0

S,問題在於jar,我只是嘗試刪除所有jar文件並添加了一個一個,它開始工作正常。感謝您的努力。 –