以下是关于HttpClient实现文件上传功能的完整攻略。
简介
HttpClient是Apache的一个开源组件,它提供了高效的、简单的、简洁的编程接口,用于发送HTTP/HTTPS请求并处理响应。支持字符集转换、错误处理、重试处理、SSL连接、连接池等。
文件上传是HTTP协议中常用的一个功能,在web开发中尤为常见。HttpClient提供了完整的封装,以方便开发人员实现和管理文件上传。
实现
- 添加HttpClient依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
- 实现文件上传
以下是一个简单的文件上传示例:
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class FileUploader {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/upload");
//设置文件
File file = new File("test.txt");
HttpEntity entity = MultipartEntityBuilder
.create()
.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName())
.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
response.close();
httpClient.close();
}
}
以上示例中,通过创建CloseableHttpClient对象并使用HttpPost对象发起POST请求。使用MultipartEntityBuilder构建multipart/form-data类型的请求内容。其中包含一个名为"file"的文件参数,参数值为一个File对象。需要通过ContentType.DEFAULT_BINARY指定参数值类型,并设置文件名为file.getName()。
示例1:Spring MVC上传文件
以Spring MVC为例,实现文件上传的过程如下:
- 添加依赖
添加Spring MVC和Apache Commons FileUpload依赖即可。
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
- 配置文件上传解析器
在Spring MVC配置文件中添加如下配置:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/> <!--设置最大上传大小为10M-->
<property name="defaultEncoding" value="UTF-8"/> <!--设置默认编码-->
</bean>
- 实现Controller
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class FileUploadController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(MultipartHttpServletRequest request, Model model) throws IOException {
List<MultipartFile> files = request.getFiles("file");
for (MultipartFile file : files) {
File dest = new File("/path/to/destination/" + file.getOriginalFilename());
FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
}
model.addAttribute("result", "success");
return "uploadResultPage";
}
}
以上示例中,在Controller接收请求中使用了MultipartHttpServletRequest和MultipartFile,MultipartFile中即为文件上传的内容。将其保存到对应路径即可。
示例2:使用HttpClient模拟POST上传请求
以下是一个使用HttpClient模拟POST上传请求的示例:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class UploadFileTest {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/upload");
File file = new File("D:\\test.docx");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
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();
}
}
}
以上示例中,构造了一个HttpPost请求,其中设置了请求URL和需要上传的文件。使用MultipartEntityBuilder构建multipart/form-data类型的请求内容。其中包含一个名为"file"的文件参数,参数值为一个File对象。需要通过ContentType.APPLICATION_OCTET_STREAM指定参数值类型,并设置文件名为file.getName()。然后将构建好的请求内容设置到HttpPost实例中。
总结
以上是关于使用HttpClient实现文件上传功能的完整攻略。可以看出,通过HttpClient实现文件上传的过程主要是构建multipart/form-data类型的请求内容,并发送到服务器。在实际开发中,可根据具体需求进行配置和调整。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:HttpClient实现文件上传功能 - Python技术站