在Java中使用CloseableHttpClient来实现附带form data参数userId实现上传文件,可以使用HttpPost
请求,然后通过MultipartEntityBuilder
来构建请求体:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
public class FileUploader {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/upload");
// 构建请求体,添加文件和form data参数
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("path/to/file")); // 添加文件
builder.addTextBody("userId", "123"); // 添加form data参数
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
// 处理响应结果
System.out.println(responseBody);
// 关闭连接
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请记得将上述代码中的http://example.com/upload
替换为实际的上传文件地址,并将path/to/file
替换为实际文件的路径。