HttpClient:模擬表單提交檔案,傳送multipart/form-data資料
阿新 • • 發佈:2019-01-10
使用HttpClient來模擬表單提交,傳送檔案
常用於非web客戶端與web後端傳輸檔案
1.pom
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version >4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency >
2.post data
public class PostMultiData {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
String uri = "http://127.0.0.1:8080/encoding/servlet/RevFileServlet";
uri="http://127.0.0.1:8080/revFile" ;
HttpPost httppost = new HttpPost(uri);
String path="C:/Users/Administrator/Desktop/study/微服務/netflix/eureka.png";
File file = new File(path);
FileBody bin = new FileBody(file);
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
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();
}
}
}