gpt4 book ai didi

java - 使用 apache cxf 发布表单

转载 作者:行者123 更新时间:2023-12-02 03:28:56 26 4
gpt4 key购买 nike

我正在尝试发布一个包含文件以及普通文本数据的表单。我为此使用 Apache CXF。下面是代码

WebClient client= WebClient.create(ROOT_URL_FILE_SERVICE);

client.type("multipart/form-data");
InputStream is= new ByteArrayInputStream(getBytes());
List<Attachment> attachments= new ArrayList();
ContentDisposition cd = new ContentDisposition("attachment;filename=image.jpg");
Attachment att= new Attachment("File", is, cd);
Attachment pageNumber= new Attachment("DATA1", MediaType.TEXT_PLAIN, "1");
Attachment OutputType= new Attachment("DATA2", MediaType.TEXT_PLAIN, "2");

attachments.add(att);
attachments.add(pageNumber);
attachments.add(OutputType);
MultipartBody body= new MultipartBody(attachments);

Response res=client.post(body);

我无法在服务器端获取任何内容(文件、DATA1、DATA2)。

我需要修改上面的代码才能使其正常工作。

最佳答案

检查您的服务器端 cxf 配置,如下所示。

@POST
@Path("/upload")
@Produces(MediaType.TEXT_XML)
public String upload(
@Multipart(value = "File", type = MediaType.APPLICATION_OCTET_STREAM) final InputStream fileStream,
@Multipart(value = "DATA1", type = MediaType.TEXT_PLAIN) final String fileNumber,
@Multipart(value = "DATA2", type = MediaType.TEXT_PLAIN) final String outputType) {
BufferedImage image;
try {
image = ImageIO.read(fileStream);
LOG.info("Received Image with dimensions {}x{} ", image.getWidth(), image.getHeight());
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}

LOG.info("Received Multipart data1 {} ", fileNumber);
LOG.info("Received Multipart data2 {} ", outputType);
return "Recieved all data";
}

测试的客户端文件

 public static void main(String[] args) throws IOException {

WebClient client = WebClient.create("http://localhost:8080/services/kp/upload");
ClientConfiguration config = WebClient.getConfig(client);
config.getInInterceptors().add(new LoggingInInterceptor());
config.getOutInterceptors().add(new LoggingOutInterceptor());
client.type("multipart/form-data");
InputStream is = FileUtils.openInputStream(new File("vCenter_del.jpg"));
List<Attachment> attachments = new ArrayList<>();
ContentDisposition cd = new ContentDisposition("attachment;filename=image.jpg");
Attachment att = new Attachment("File", is, cd);
Attachment pageNumber = new Attachment("DATA1", MediaType.TEXT_PLAIN, "1");
Attachment OutputType = new Attachment("DATA2", MediaType.TEXT_PLAIN, "2");

attachments.add(att);
attachments.add(pageNumber);
attachments.add(OutputType);
MultipartBody body = new MultipartBody(attachments);

Response res = client.post(body);

String data = res.readEntity(String.class);
System.out.println(data);
}

注意: 简而言之,如果 content-id 不匹配,如果 file、data1 或 content-type,服务器可能在这两种情况下都不会收到数据,您将收到相应的错误,例如 400 和分别为 415。

关于java - 使用 apache cxf 发布表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38375216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com