Android-上傳圖片(二)_HttpClient
上篇博文中記錄了使用HttpURLConnection模擬HTTP請求上傳文件到服務端 Android-上傳圖片(-)_HttpURLConnection
本篇博文中將使用Apache HttpClient實現相同的功能。
HttpClient官方quickstart文檔
詳情請移步本人GITHUB
客戶端核心代碼如下:
HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); MultipartEntity multipartEntity = new MultipartEntity(); FileBody fileBody = new FileBody(file); // file 是服務端讀取文件的 key 對應的 multipartEntity.addPart("file", fileBody); httpPost.setEntity(multipartEntity); try { HttpResponse response = httpClient.execute(httpPost); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 打印服務端返回的消息 String retMessage = EntityUtils.toString(response.getEntity()); LogUtils.d(retMessage); // 發送消息,更新主線程 Message message = new Message(); message.what = 2 ; message.obj = retMessage; handler.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Android
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。