以 QAnthing 上传文件(POST)接口为例,展示Java如何调用上传文件接口。
接口文档如下:
QAnthign接口文档地址
上代码:
RestTemplate 版
/**
* * @param url 接口地址
* @param filePath 文件本地路径
*/
public void uploadFile(String url, String filePath) {
// 使用RestTemplate上传文件
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
// 准备MultiValueMap来保存文件和其他表单字段
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("files", new FileSystemResource(filePath));
body.add("user_id", "zzp");
body.add("kb_id", "KBb1dd58e8485443ce81166d24f6febda7");
body.add("mode", "soft");
// 创建HttpEntity
org.springframework.http.HttpEntity<MultiValueMap<String, Object>> requestEntity = new org.springframework.http.HttpEntity<>(body, headers);
// 发送请求
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity,
String.class);
// 输出响应
System.out.println("Response: " + response.getBody());
}
private File downloadFile(String fileUrl) throws IOException {
try (InputStream in = new URL(fileUrl).openStream()) {
File tempFile = Files.createTempFile("uploaded-", ".tmp").toFile();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
System.out.println("File downloaded to: " + tempFile.getAbsolutePath());
return tempFile;
}
}
OkHttp 版
private void uploadFile(File file, String fileName, String fileSuffix, String url) throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
//MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
// .addFormDataPart("user_id", "zzp") // .addFormDataPart("kb_id", "KB3e7062d6d6c54b10af79164009e736d8_240625") // .addFormDataPart("mode", "soft"); //for (File file : fileList) { // builder.addFormDataPart("files", file.getName(), // RequestBody.create(MediaType.parse("application/octet-stream"), // file)); //} //RequestBody body = builder.build(); RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("files", fileName + "." + fileSuffix,
RequestBody.create(MediaType.parse("application/octet-stream"),
file))
.addFormDataPart("user_id", "zzp")
.addFormDataPart("kb_id", "KBb1dd58e8485443ce81166d24f6febda7")
.addFormDataPart("mode", "soft")
.build();
Request request = new Request.Builder()
.url(url)
.method("POST", body)
.build();
Response response = client.newCall(request).execute();
System.out.println(response);
}
如果文件是互联网资源文件可以使用如下代码进行下载:
/**
* 下载文件
*
* @param fileUrl
* @return
* @throws IOException
*/
private File downloadFile(String fileUrl) throws IOException {
try (InputStream in = new URL(fileUrl).openStream()) {
File tempFile = Files.createTempFile("uploaded-", ".tmp").toFile();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
System.out.println("File downloaded to: " + tempFile.getAbsolutePath());
return tempFile;
}
}
/**
* 删除临时文件
*
* @param file
* @throws IOException
*/
private void delFile(File file) throws IOException {
// 删除临时文件
if (file.delete()) {
System.out.println("Temporary file deleted: " + file.getAbsolutePath());
} else {
System.out.println("Failed to delete temporary file: " + file.getAbsolutePath());
}
}