gpt4 book ai didi

java - CXF "No Message body reader found"用于 POST 服务中的字节数组参数

转载 作者:行者123 更新时间:2023-11-30 09:00:27 28 4
gpt4 key购买 nike

我正在尝试编写一个服务,该服务负责通过将文件作为 POST 实体中的字节数组来上传文件。这是我的代码

我的 CXF 服务

@Path("MyTest")
public class TestService {
@POST
public String MyPost(Byte[] bytes){
System.out.println("Service invoked");
return "Hello, I am a POST response";
}
}

我的客户

File image = new File("C:\\snake.jpg");
FileInputStream is = new FileInputStream(image);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] fileInBytes = bos.toByteArray();

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080/MyApp");
target = target.path("MyTest");
Response response = target.request().post(Entity.entity(fileInBytes, MediaType.APPLICATION_OCTET_STREAM));

InputStream i = (InputStream) response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(i));
System.out.println(br.readLine());

这是我得到的错误

SEVERE: No message body reader has been found for class [Ljava.lang.Byte;, ContentType: application/octet-stream
Nov 06, 2014 4:02:50 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: javax.ws.rs.WebApplicationException: HTTP 415 Unsupported Media Type
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1298)
...

有什么想法吗?有没有更好的方法来做文件上传服务?

谢谢

最佳答案

您可以使用InputStream

@POST
public String MyPost(InputStream is) throws IOException {
BufferedImage image = ImageIO.read(is);
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image)));
System.out.println("Service invoked");
return "Hello, I am a POST response";
}

此外,在您的客户端代码中,您实际上并未向输出流写入任何内容。应该更像一些

FileInputStream is = new FileInputStream(image);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] fileInBytes = buffer.toByteArray();

Response response = target.request().post(Entity.entity(fileInBytes,
MediaType.APPLICATION_OCTET_STREAM));

更新

可以实际使用字节数组。你只需要使用原始的 byte[]

@POST
public String MyPost(byte[] bytes) throws IOException {
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bytes)));
System.out.println("Service invoked");
return "Hello, I am a POST response";
}

甚至可以使用 File

@POST
public String MyPost(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image)));
System.out.println("Service invoked");
return "Hello, I am a POST response";
}

JAX-RS 在磁盘上创建一个用于输入的临时文件。它从网络缓冲区读取并将读取的字节保存到这个临时文件中。

它们都有效。选择你的毒药

关于java - CXF "No Message body reader found"用于 POST 服务中的字节数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26784038/

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