在Android中,可以使用HTTP协议来在服务器和客户端之间传输文件。以下是一个示例代码,演示了如何在Android中上传和下载文件:
public class FileUploadTask extends AsyncTask {
@Override
protected Void doInBackground(String... params) {
String filePath = params[0];
String uploadUrl = params[1];
try {
File file = new File(filePath);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uploadUrl);
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", fileBody);
httpPost.setEntity(builder.build());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.d("FileUpload", "Response: " + responseStr);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// 上传完成后的操作
}
}
使用示例:
String filePath = "/path/to/file";
String uploadUrl = "http://example.com/upload";
FileUploadTask fileUploadTask = new FileUploadTask();
fileUploadTask.execute(filePath, uploadUrl);
public class FileDownloadTask extends AsyncTask {
@Override
protected Void doInBackground(String... params) {
String downloadUrl = params[0];
String saveFilePath = params[1];
try {
URL url = new URL(downloadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// 下载完成后的操作
}
}
使用示例:
String downloadUrl = "http://example.com/file.txt";
String saveFilePath = "/path/to/save/file.txt";
FileDownloadTask fileDownloadTask = new FileDownloadTask();
fileDownloadTask.execute(downloadUrl, saveFilePath);
注意:在使用这些代码示例之前,请确保已经添加必要的网络权限到你的Android清单文件中。