編輯:關於 Android 程式設計
檔案上傳是許多應用的必備功能。以下這份 UploadUtil 已將註解寫得相當清楚,透過 HttpURLConnection 以 multipart/form-data 方式 POST 上傳,隨取即用,方便隨時參考。
public class UploadUtil {
private static final String TAG = "TTTTTT upload";
private static final int TIME_OUT = 10 * 1000; // 超時時間
private static final String CHARSET = "utf-8"; // 設定編碼
public static String uploadFile(File file, String RequestURL) {
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 邊界標識,隨機生成
String CONTENT_TYPE = "multipart/form-data"; // 內容類型
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允許輸入流
conn.setDoOutput(true); // 允許輸出流
conn.setUseCaches(false); // 不使用緩存
conn.setRequestMethod("POST"); // 請求方式
conn.setRequestProperty("Charset", CHARSET);
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
if (file != null) {
// 當檔案不為空,包裝並上傳
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.flush();
// 取得回應碼,200 代表成功
int res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
if (res == 200) {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
}
} else {
Log.e(TAG, "file not found!");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
整段邏輯先設定連線參數與邊界標識,接著以串流方式讀取檔案內容寫入輸出流,最後依據回應碼判斷上傳是否成功並解析伺服器回傳的結果。
Android 狀態欄通知詳解:Notification 與 NotificationManager
在 Android 中發送一條狀態欄通知其實很方便。本文將帶你了解通知的發送方式,以及究竟有哪些參數可以自定義。 發送通知離不開兩個核心類:NotificationMan
Android 高德定位集成全流程詳解
說到定位,大家應該都不陌生。如今幾乎每款 App 都離不開定位功能。Android 本身也提供了定位能力(LocationManager),但由於某些众所周知的原因,原生
Android 實戰:SwipeRefreshLayout 下拉刷新 + 瀑布流 RecyclerView + ButterKnife 綁定
本文記錄三個實用技巧:SwipeRefreshLayout 下拉刷新與上拉加載、StaggeredGridLayoutManager 瀑布流佈局,以及 ButterKni
解決 Android ViewPager 出現重複數據的問題
最近在做的的新聞客戶端用到了 ViewPager。如今 Android Studio 整合得很完善,自動產生了許多不必手寫的程式碼。使用過程中,我碰到了一件怪事:View