[Android] 使用 HttpClient post 資料到伺服器

其實 Android 有內建 HttpClient 的 library,但是實在是太舊了(4.0beta2),所以用了熱心人士重新包裝過後的 新版,雖然有點大,不過把常用的都包進去了,應該不會踩到一些陳年老 bug。

下面的 code 還有用到 Apache Commons IO,這裡 可以下載。

private void postData(String url, String filepath, String filename ) throws Exception {
        
        byte[] data;
        
        HttpPost httppost = new HttpPost(url);
        HttpClient httpclient = HttpClientBuilder.create().build();
        
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        
        InputStream inputStream = new FileInputStream(filepath);
        data = IOUtils.toByteArray(inputStream);
        InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), filename);
        
        //entityBuilder.addTextBody("action", "test");
        //entityBuilder.addBinaryBody("file", file);
        entityBuilder.addPart("file", inputStreamBody);

        HttpEntity entity = entityBuilder.build();
        httppost.setEntity(entity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity httpEntity = response.getEntity();

        String result = EntityUtils.toString(httpEntity);
        Log.d("uploader", result);
        
}

DefaultHttpClient 已經過時了,不建議使用,所以用 HttpClientBuilder 代替。

[Android] 使用 HttpClient post 資料到伺服器