通过 JDK 11 HttpClient 发送 multipar
2022-05-11 本文已影响0人
bowen_wu
Dependency
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<scope>test</scope>
</dependency>
Controller
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.inject.Inject;
import java.io.IOException;
@RestController
@RequestMapping("/api/v1")
public class UploadController {
private final FileService fileService;
@Inject
public UploadController(FileService fileService) {
this.fileService = fileService;
}
@PostMapping(value = "/file/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
return fileService.upload(file);
}
}
Integration Test
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.springframework.http.HttpHeaders;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublisher;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.file.Paths;
class UploadIntegrationTest {
public HttpResponse<String> sendUploadFileRequest(String adminCookie) throws URISyntaxException, IOException, InterruptedException {
URL url = getClass().getClassLoader().getResource("static/200.jpeg");
HttpEntity httpEntity = MultipartEntityBuilder
.create()
.addBinaryBody("file", Paths.get(url.toURI()).toFile(), ContentType.IMAGE_JPEG, "200.jpeg")
.build();
Pipe pipe = Pipe.open();
new Thread(() -> {
try (OutputStream outputStream = Channels.newOutputStream(pipe.sink())) {
// Write the encoded data to the pipeline.
httpEntity.writeTo(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
BodyPublisher bodyPublisher = BodyPublishers.ofInputStream(() -> Channels.newInputStream(pipe.source()));
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8080/api/v1/video/upload"))
.method("POST", bodyPublisher)
.header(HttpHeaderf.CONTENT_TYPE, httpEntity.getContentType().getValue())
.header(HttpHeaders.COOKIE, adminCookie)
.build();
return client.send(request, BodyHandlers.ofString());
}
}
参考
https://www.springcloud.io/post/2022-04/httpclient-multipart/#gsc.tab=0