birdy
birdy

Reputation: 9646

How to accept a byte[] as a response to POST

I am making a POST request to a service and sending a file along. On response from this POST request the service responds back with a byte[]. How can I get access to the returning byte[] in my code?

This is how I'm doing the POST in my client code using apache-commons-httpclient

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);
}

The service is also written by me and I have control over it. It is written in grails and looks like this:

//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
}

Upvotes: 1

Views: 881

Answers (1)

user784540
user784540

Reputation:

Use Base64 encoding to send response data to your client.

Your client receives Base64 string and decodes it to the byte array.

Upvotes: 1

Related Questions