Android-上传图片(二)_HttpClient
生活随笔
收集整理的這篇文章主要介紹了
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 <input type="file" name="file" /> 對應的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();}總結
以上是生活随笔為你收集整理的Android-上传图片(二)_HttpClient的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android-上传图片(-)_Http
- 下一篇: Android模拟多线程下载