api ‘org.apache.httpcomponents.client5:httpclient5:5.2.2’
api ‘org.apache.commons:commons-compress:1.24.0’
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.FileNameUtils;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.util.Assert;
import java.io.File;
import java.nio.charset.StandardCharsets;
public class Test {
@SneakyThrows
public static void main(String[] args) {
File file = new File("C:\\Users\\admin\\Desktop\\temp.mp4");
CloseableHttpClient httpClient = HttpClients.createDefault();
try(httpClient) {
HttpPost httpPost = new HttpPost("https://xxx.com//upload");
httpPost.setHeader("token", "xxx");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("account", "1233221");
// 文件名
builder.addBinaryBody("filename", FileNameUtils.getBaseName(file.getName()).getBytes(StandardCharsets.UTF_8));
// 文件
builder.addPart("file", new FileBody(file));
httpPost.setEntity(builder.build());
CloseableHttpResponse response = httpClient.execute(httpPost);
Assert.isTrue(response.getCode() == HttpStatus.SC_OK, response.getReasonPhrase());
String jsonStr = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.displayName());
System.out.println(jsonStr);
}
}
}