我正在向服务发出 POST
请求并发送文件。响应此 POST
请求时,服务会使用 byte[]
进行响应。如何访问代码中返回的 byte[]
?
这就是我使用 apache-commons-httpclient 在客户端代码中执行 POST
的方式
public void sendFile(InputStream is) throws Exception {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://service:8080/myservice/request/testimage");
ByteArrayPartSource bpa = new ByteArrayPartSource("s.jpg",IOUtils.toByteArray(is));
Part[] parts = new Part[] {
new FilePart("myFile", bpa)
};
method.setRequestEntity(
new MultipartRequestEntity(parts, method.getParams())
);
client.executeMethod(method);
}
该服务也是我编写的,我可以控制它。它是用 grails 编写的,如下所示:
//Domain
class Image {
byte[] myFile
static constraints = {
myFile maxSize: 1024 * 1024 * 2
}
}
//Controller
def testimage() {
def img = new Image(params)
byte[] fileBytes = service.performChangesToFile(img.myFile)
render fileBytes
}
最佳答案
使用Base64 encoding将响应数据发送给您的客户端。
您的客户端接收 Base64 字符串并将其解码为字节数组。
关于java - 如何接受 byte[] 作为对 POST 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24490354/