【问题标题】:How to accept a byte[] as a response to POST如何接受 byte[] 作为对 POST 的响应
【发布时间】:2014-06-30 12:38:33
【问题描述】:

我正在向服务发出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
}

【问题讨论】:

  • method.responseBody 应该返回 byte[]

标签: java web-services grails bytearray apache-commons-httpclient


【解决方案1】:

使用Base64 encoding 将响应数据发送到您的客户端。

您的客户端接收 Base64 字符串并将其解码为字节数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2016-10-16
    • 2014-04-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多