編輯:關於Android編程
import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class UploadUtil { private static final String TAG = "UploadUtil"; public static String upload(String uploadUrl, String uploadFile) { String fileName = ""; int pos = uploadFile.lastIndexOf("/"); if (pos >= 0) { fileName = uploadFile.substring(pos + 1); } String end = "\r\n"; String Hyphens = "--"; String boundary = "WUm4580jbtwfJhNp7zi1djFEO3wNNm"; try { URL url = new URL(uploadUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream ds = new DataOutputStream(conn.getOutputStream()); ds.writeBytes(Hyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + fileName + "\"" + end); ds.writeBytes(end); FileInputStream fStream = new FileInputStream(uploadFile); // 每次寫入1024字節 int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; // 將文件數據寫入到緩沖區 while((length = fStream.read(buffer)) != -1) { ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(Hyphens + boundary + Hyphens + end); fStream.close(); ds.flush(); // 獲取返回內容 InputStream is = conn.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } ds.close(); return "SUCC"; } catch (Exception e) { e.printStackTrace(); return "上傳失敗:" + e.getMessage(); } } }
import java.io.File; import com.example.exmupload.MainActivity; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.RequestParams; import android.util.Log; public class AsyncUtil { private static final String TAG = "AsyncUtil"; public static String upload(final MainActivity act, String uploadServlet, String filePath, boolean isBinary) { try { //服務端的commons-fileupload只支持multipart/form-data方式 //application/octet-stream表示任意的二進制文件,包括圖片、音頻、視頻、壓縮文件等等 String contentType = "application/octet-stream"; //String contentType = "multipart/form-data"; RequestParams params = new RequestParams(); if (isBinary == true) { params.put("file", new File(filePath), contentType); } else { params.put("file", new File(filePath)); } Log.d(TAG, "contentType="+contentType); AsyncHttpClient client = new AsyncHttpClient(); //AsyncHttpResponseHandle不在ui線程運行,不能直接操作ui //如果在此處定義AsyncHttpResponseHandle對象,則運行報錯: //java.lang.IllegalArgumentException: Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead. client.post(uploadServlet, params, act.mAsyncHandler); return "uploadByFile"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } // //下面代碼在MainActivity.java中定義 // public AsyncHttpResponseHandler mAsyncHandler = new AsyncHttpResponseHandler() { // @Override // public void onSuccess(int status, Header[] headers, byte[] data) { // String result = "文件上傳成功!"; // Message msg = Message.obtain(); // msg.what = ASYNC; // msg.obj = result; // mHandler.sendMessage(msg); // } // // @Override // public void onFailure(int status, Header[] headers, byte[] data, Throwable e) { // String result = "文件上傳失敗!"+e.getMessage(); // Message msg = Message.obtain(); // msg.what = ASYNC; // msg.obj = result; // mHandler.sendMessage(msg); // } // }; }
import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.example.exmupload.MainActivity; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.http.Multipart; import retrofit2.http.PartMap; import retrofit2.http.POST; import android.util.Log; import android.webkit.MimeTypeMap; public class RetrofitUtil { private static final String TAG = "RetrofitUtil"; public interface ApiInterface { //這裡的POST是不帶ip也不帶域名的地址,下面uploadHost才帶ip/域名和端口,如http://192.168.0.212:8080/ @Multipart @POST("UploadTest/uploadServlet") Callupload(@PartMap Map params); } public static void upload(final MainActivity act, String uploadHost, String filePath) { File file1 = new File(filePath); Retrofit retrofit = new Retrofit.Builder().baseUrl(uploadHost).build(); ApiInterface apiService = retrofit.create(ApiInterface.class); // 獲取文件真實的內容類型 // String mimeType = MimeTypeMap.getSingleton() // .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(file1.getPath())); // RequestBody fileBody = RequestBody.create(MediaType.parse(mimeType), filePath); RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), filePath); Map params = new HashMap<>(); // 如果要上傳多個文件,可對該Map對象進行put操作 params.put("file\"; filename=\"" + file1.getName() + "", fileBody); Call call = apiService.upload(params); call.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { try { String jsonString = new String(response.body().bytes()); // 這就是返回的json字符串了。 Log.d(TAG, "onResponse succ : "+jsonString); act.notify(act.RETROFIT, "onResponse succ "+jsonString); } catch (IOException e) { e.printStackTrace(); act.notify(act.RETROFIT, "onResponse "+e.getMessage()); } } @Override public void onFailure(Call call, Throwable throwable) { Log.d(TAG, "onFailure : "+throwable.getMessage()); act.notify(act.RETROFIT, "onFailure "+throwable.getMessage()); } }); } }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("request.getContentType()="+request.getContentType()); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); Writer o = response.getWriter(); //首先判斷Content-Type是不是multipart/form-data。同時也判斷了form的提交方式是不是post if (ServletFileUpload.isMultipartContent(request)) { request.setCharacterEncoding("utf-8"); // 實例化一個硬盤文件工廠,用來配置上傳組件ServletFileUpload DiskFileItemFactory factory = new DiskFileItemFactory(); //設置文件存放的臨時文件夾,這個文件夾要真實存在 File fileDir = new File("../webapps/"); if (fileDir.isDirectory() && fileDir.exists()==false) { fileDir.mkdir(); } factory.setRepository(fileDir); //設置最大占用的內存 factory.setSizeThreshold(1024000); //創建ServletFileUpload對象 ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setHeaderEncoding("utf-8"); //設置單個文件最大值byte sfu.setFileSizeMax(102400000); //所有上傳文件的總和最大值byte sfu.setSizeMax(204800000); Listitems = null; try { items = sfu.parseRequest(request); System.out.println("items.size()="+items.size()); } catch(Exception e) { e.printStackTrace(); } Iterator iter = items==null?null:items.iterator(); //文件上傳後存放的路徑目錄 File dir = new File("D:/"); if (dir.exists()==false) { dir.mkdirs(); } while (iter!=null && iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //如果傳過來的是普通的表單域 System.out.print("普通的表單域:"); System.out.print(new String(item.getFieldName()) + " "); System.out.println(new String(item.getString("UTF-8"))); } else if (!item.isFormField()) { //文件域 System.out.println("源文件:" + item.getName()); String fileName = item.getName(); if (fileName.indexOf("\\") >= 0) { fileName = item.getName().substring(item.getName().lastIndexOf("\\")); } BufferedInputStream in = new BufferedInputStream(item.getInputStream()); BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new File(dir.getAbsolutePath()+ fileName))); Streams.copy(in, out, true); o.write("文件上傳成功"); } } } else { System.out.println("表單的Content-Type錯誤"); } } }
import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPUtil { private static String mUurl; private static String mPort; private static String mUsername; private static String mPassword; public static void setUser(String url, String port, String username, String password) { mUurl = url; mPort = port; mUsername = username; mPassword = password; } public static String upload(String remotePath, String filePath, String fileName) { FTPClient ftpClient = new FTPClient(); String result = "SUCC"; try { ftpClient.connect(mUurl, Integer.parseInt(mPort)); boolean loginResult = ftpClient.login(mUsername, mPassword); int returnCode = ftpClient.getReplyCode(); if (loginResult && FTPReply.isPositiveCompletion(returnCode)) { //登錄成功 ftpClient.makeDirectory(remotePath); // 設置上傳目錄 ftpClient.changeWorkingDirectory(remotePath); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("UTF-8"); ftpClient.enterLocalPassiveMode(); FileInputStream fis = new FileInputStream(filePath + fileName); ftpClient.storeFile(fileName, fis); } else { //登錄失敗 result = "FAIL"; } } catch (IOException e) { e.printStackTrace(); result = "FTP客戶端出錯!" + e.getMessage(); } finally { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); result = "關閉FTP連接發生異常!" + e.getMessage(); } } return result; } }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import java.util.Vector; import android.util.Log; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelSftp.LsEntry; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class SFTPUtil { private static final String TAG = "SFTPUtil"; public static int SUCC = 0; public static int FAIL = -1; //連接sftp服務器 public static ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); Session session = jsch.getSession(username, host, port); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; Log.d(TAG, "Connected to " + host + "."); } catch (Exception e) { e.printStackTrace(); } return sftp; } //上傳文件 public static String upload(ChannelSftp sftp, String directory, String uploadFile) { try { sftp.cd(directory); File file = new File(uploadFile); sftp.put(new FileInputStream(file), file.getName()); Log.d(TAG, "Upload succ. " + uploadFile); return "SUCC"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } //下載文件 public static int download(ChannelSftp sftp, String directory, String downloadFile, String saveFile) { try { sftp.cd(directory); File file = new File(saveFile); sftp.get(downloadFile, new FileOutputStream(file)); Log.d(TAG, "Download succ. " + downloadFile); return SUCC; } catch (Exception e) { e.printStackTrace(); return FAIL; } } //刪除文件 public static int delete(ChannelSftp sftp, String directory, String deleteFile) { try { sftp.cd(directory); sftp.rm(deleteFile); Log.d(TAG, "Delete succ. " + deleteFile); return SUCC; } catch (Exception e) { e.printStackTrace(); return FAIL; } } //列出目錄下的文件 public static Vector listFiles(ChannelSftp sftp, String directory) throws SftpException { //Vector容器內部保存的是LsEntry類型對象。 return sftp.ls(directory); } }
import java.util.Map; import org.apache.http.Header; import com.aqi00.lib.dialog.FileSelectFragment; import com.aqi00.lib.dialog.FileSelectFragment.FileSelectCallbacks; import com.example.exmupload.util.AsyncUtil; import com.example.exmupload.util.FTPUtil; import com.example.exmupload.util.RetrofitUtil; import com.example.exmupload.util.SFTPUtil; import com.example.exmupload.util.UploadUtil; import com.jcraft.jsch.ChannelSftp; import com.loopj.android.http.AsyncHttpResponseHandler; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener,FileSelectCallbacks { private static final String TAG = "MainActivity"; private static TextView tv_filename; private Button btn_select; private Button btn_upload; private Button btn_async; private Button btn_retrofit; private Button btn_ftp; private Button btn_sftp; private static TextView tv_result; public static String mUploadHost = "http://192.168.0.212:8080/"; public static String mUploadService = "UploadTest/uploadServlet"; private String mServletUrl = mUploadHost + mUploadService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_filename = (TextView) findViewById(R.id.tv_filename); btn_select = (Button) findViewById(R.id.btn_select); btn_upload = (Button) findViewById(R.id.btn_upload); btn_async = (Button) findViewById(R.id.btn_async); btn_retrofit = (Button) findViewById(R.id.btn_retrofit); btn_ftp = (Button) findViewById(R.id.btn_ftp); btn_sftp = (Button) findViewById(R.id.btn_sftp); tv_result = (TextView) findViewById(R.id.tv_result); btn_select.setOnClickListener(this); btn_upload.setOnClickListener(this); btn_async.setOnClickListener(this); btn_retrofit.setOnClickListener(this); btn_ftp.setOnClickListener(this); btn_sftp.setOnClickListener(this); } @Override public void onClick(View v) { String file_path = tv_filename.getText().toString().trim(); if (v.getId() == R.id.btn_select) { FileSelectFragment.show(this, new String[]{"jpg","png","gif","txt"}, null); return; } if (file_path.length() <= 0) { Toast.makeText(this, "請選擇要上傳的文件", Toast.LENGTH_LONG).show(); return; } if (v.getId() == R.id.btn_upload) { tv_result.setText("開始HttpURLConnection上傳"); new ConnnectionThread(file_path).start(); } else if (v.getId() == R.id.btn_async) { tv_result.setText("開始async上傳"); new AsyncThread(file_path).start(); } else if (v.getId() == R.id.btn_retrofit) { tv_result.setText("開始retrofit上傳"); new RetrofitThread(file_path).start(); } else if (v.getId() == R.id.btn_ftp) { new FTPThread(file_path).start(); } else if (v.getId() == R.id.btn_sftp) { new SFTPThread(file_path).start(); } } public void notify(int type, String message) { Message msg = Message.obtain(); msg.what = type; msg.obj = message; mHandler.sendMessage(msg); } private class ConnnectionThread extends Thread { private String mFilePath; public ConnnectionThread(String file_path) { mFilePath = file_path; } @Override public void run() { String result = UploadUtil.upload(mServletUrl, mFilePath); MainActivity.this.notify(COMMON, "upload :" + result); } } private class AsyncThread extends Thread { private String mFilePath; public AsyncThread(String file_path) { mFilePath = file_path; } @Override public void run() { String result = AsyncUtil.upload(MainActivity.this, mServletUrl, mFilePath, true); MainActivity.this.notify(ASYNC, "upload :" + result); } } public AsyncHttpResponseHandler mAsyncHandler = new AsyncHttpResponseHandler() { @Override public void onSuccess(int status, Header[] headers, byte[] data) { MainActivity.this.notify(ASYNC, "文件上傳成功!"); } @Override public void onFailure(int status, Header[] headers, byte[] data, Throwable e) { MainActivity.this.notify(ASYNC, "文件上傳失敗!"+e.getMessage()); } }; private class RetrofitThread extends Thread { private String mFilePath; public RetrofitThread(String file_path) { mFilePath = file_path; } @Override public void run() { RetrofitUtil.upload(MainActivity.this, mUploadHost, mFilePath); } } private class FTPThread extends Thread { private String mFilePath; public FTPThread(String file_path) { mFilePath = file_path; } @Override public void run() { String filepath = mFilePath.substring(0, mFilePath.lastIndexOf("/")+1); String filename = mFilePath.substring(mFilePath.lastIndexOf("/")+1); FTPUtil.setUser("172.16.16.146", "21", "testftp", "testftp"); String result = FTPUtil.upload("/home/testftp", filepath, filename); MainActivity.this.notify(FTP, result); } } private class SFTPThread extends Thread { private String mFilePath; public SFTPThread(String file_path) { mFilePath = file_path; } @Override public void run() { ChannelSftp sftp = SFTPUtil.connect("172.16.16.133", 22, "oracle", "oracle"); String result = SFTPUtil.upload(sftp, "/home/oracle", mFilePath); MainActivity.this.notify(SFTP, result); } } public int COMMON = 0; public int ASYNC = 1; public int RETROFIT = 2; public int FTP = 3; public int SFTP = 4; @SuppressLint("HandlerLeak") public Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { String result = (String) msg.obj; if (msg.what == COMMON) { tv_result.setText(tv_result.getText().toString()+"\n"+result); } else if (msg.what == ASYNC) { tv_result.setText(tv_result.getText().toString()+"\n"+result); } else if (msg.what == RETROFIT) { tv_result.setText(tv_result.getText().toString()+"\n"+result); } else if (msg.what == FTP) { showTip("FTP文件上傳結果:"+result); } else if (msg.what == SFTP) { showTip("sftp文件上傳結果:"+result); } } }; private void showTip(String desc) { Toast.makeText(getApplicationContext(), desc, Toast.LENGTH_SHORT).show(); } @Override public void onConfirmSelect(String absolutePath, String fileName, Mapmap_param) { String path = absolutePath + "/" + fileName; tv_filename.setText(path); } @Override public boolean isFileValid(String absolutePath, String fileName, Map map_param) { return true; } }
小編一直任務將web和android組件結合起來做應用可以事半功倍,html5一來就更有說服力了,特別是對於以前從事web開發的兄弟來說 1. webview加入布局文件
Google即將發布的Android7.0的預覽版Android_N為我們增加了許多新的特性,其中包括多窗口的支持、通知欄支持直接回復、網絡數據節省開關、以及新的DOZE
AndFix原理AndFix的原理就是通過c++指針進行方法的替換,把有bug的方法替換成補丁文件中的方法。方法替換過程:源碼解析解析源碼從使用的方法一一解析。在自定義A
關鍵部分代碼如下 1、Spinnner 在布局文件中: 定義對象: private