我正在尝试使用Multipart Entity上传视频文件。对于使用Multipart Entity方法,有人提到我应该使用以下jar文件httpclient、httpmime、httpcore。但在添加httpcore jar文件时,我无法运行我的项目,它在我的控制台中引发了以下错误。
在删除这个特定的jar时,当我尝试运行应用程序时,我的日志在代码中显示以下错误。
这是我的代码供您参考:
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("abc@gmail.com"));
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时会出现这个错误,我该如何克服这些。。。???
或者有什么替代方案可以让它发挥作用吗????
以下代码经过测试,适用于从Android上传视频。
正如Knossos在对你的问题的评论中所说,现在安卓系统中有更新的、更推荐的HTTP库,这毫无价值,尽管你可能需要检查它们是否正确处理了多部分消息。Android中HTTP的一个很好的概述(它有一个有趣的历史)如下: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);
}
}