在这个教程中,我们将一步步教你如何在Eclipse环境中为Android设备编写一个应用程序,该应用程序能够通过HTTP POST请求上传文件到服务器。这个过程包括设置项目、编写代码以及测试应用程序。
1. 环境准备
在开始之前,请确保你已经安装了以下工具:
Java Development Kit (JDK)
Android SDK
Eclipse IDE
Android开发工具插件(ADT)
2. 创建新项目
打开Eclipse,选择“File” > “New” > “Android Project”。
在“Create New Project”窗口中,填写项目名称(例如,
FileUploadApp
),选择项目位置,然后点击“Next”。
在“Build Target”窗口中,选择你想要支持的最低API级别,然后点击“Next”。
在“Select Project Template”窗口中,选择“Empty Activity”,然后点击“Finish”。
3. 配置网络权限
在项目的
AndroidManifest.xml
文件中,添加网络权限:
4. 设计布局
在
res/layout/activity_main.xml
文件中,设计一个简单的布局,包括一个按钮用于选择文件,一个按钮用于上传文件,以及一个文本视图用于显示上传状态。
5. 编写代码
在
MainActivity.java
文件中,编写代码以处理文件选择和上传。
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
private static final int FILE_PICKER_REQUEST = 1;
private Button btnSelectFile, btnUploadFile;
private TextView tvStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelectFile = findViewById(R.id.btnSelectFile);
btnUploadFile = findViewById(R.id.btnUploadFile);
tvStatus = findViewById(R.id.tvStatus);
btnSelectFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(“*/*”);
startActivityForResult(intent, FILE_PICKER_REQUEST);
}
});
btnUploadFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (fileUri != null) {
uploadFile(fileUri);
} else {
tvStatus.setText(“请先选择文件”);
}
}
});
}
private Uri fileUri;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_PICKER_REQUEST && resultCode == RESULT_OK) {
fileUri = data.getData();
tvStatus.setText(“文件已选择”);
}
}
private void uploadFile(Uri fileUri) {
String filePath = getRealPathFromURI(fileUri);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
FileInputStream fileInputStream = null;
String boundary = Long.toHexString(System.currentTimeMillis()); // 随机生成边界
String twoHyphens = “–“;
String newLine = “\r\n”;
try {
URL url = new URL(“http://yourserver.com/upload”);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(“POST”);
connection.setRequestProperty(“Connection”, “Keep-Alive”);
connection.setRequestProperty(“Content-Type”, “multipart/form-data; boundary=” + boundary);
connection.setDoOutput(true);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + newLine);
outputStream.writeBytes(“Content-Disposition: form-data; name=\”file\”; filename=\”” + filePath + “\”” + newLine);
outputStream.writeBytes(“Content-Type: ” + getMIMEType(filePath) + newLine);
outputStream.writeBytes(newLine);
fileInputStream = new FileInputStream(filePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.writeBytes(newLine);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + newLine);
outputStream.flush();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
tvStatus.setText(“文件上传成功”);
} else {
tvStatus.setText(“文件上传失败”);
}
} catch (IOException e) {
e.printStackTrace();
tvStatus.setText(“上传出错:” + e.getMessage());
} finally {
try {
if (outputStream != null) outputStream.close();
if (fileInputStream != null) fileInputStream.close();
if (connection != null) connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private String getMIMEType(String fileUri) {
String type = “*/*”;
String extension = MimeTypeMap.getFileExtensionFromUrl(fileUri);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMIMETypeFromExtension(extension);
}
return type;
}
}
6. 测试应用程序
连接你的Android设备,并确保它已经启用USB调试。
运行应用程序。
点击“选择文件”按钮,从设备中选择一个文件。
点击“上传文件”按钮,等待文件上传完成。
以上步骤展示了如何在Eclipse中创建一个简单的Android应用程序,用于通过HTTP POST请求上传文件。记得将服务器地址替换为你的实际服务器地址,并根据需要调整文件上传逻辑。