1. 程式人生 > >HttpClient4.x 檔案上傳

HttpClient4.x 檔案上傳

演示

gradle專案

compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'

maven專案

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

上傳

HttpClient HTTP_CLIENT = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost/file/upload");
try {
   final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
   multipartEntity.setCharset(Charset.forName("utf-8"));
   multipartEntity.setMode(HttpMultipartMode.BROWSER
_COMPATIBLE); //for (String[] nameValue : datas) {//普通data欄位 // multipartEntity.addPart(nameValue[0], new StringBody(nameValue[1], ContentType.APPLICATION_JSON)); //} multipartEntity.addBinaryBody("file", file);//檔案欄位 httpPost.setEntity(multipartEntity.build()); //httpPost.setHeader("token", token);//設定請求頭
String result = EntityUtils.toString(HTTP_CLIENT.execute(httpPost).getEntity()); } catch (IOException e) { e.printStackTrace(); }