上篇博文中记录了使用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(); }