public void uploadFile(String url,String fileName) throws Exception{
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPut httpput = new HttpPut(url);
FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httpput.setEntity(reqEntity);
System.out.println("executing request " + httpput.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpput);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
一下是pom中需要用到的依赖
<!-- -- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> -->
<dependency>
<groupId>Id>org.apache.httpcomponentnents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- -- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime --> -->
<dependency>
<groupId>Id>org.apache.httpcomponentnents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.6</version>
上传文件到指定URL(put方式,其他类似)
最新推荐文章于 2024-12-02 10:55:17 发布