HttpClient4.x 文件上传

演示

gradle项目

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

maven项目

<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.5.3version>
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();
}

你可能感兴趣的:(java)