Setting HTTP headers on RESTeasy requests with attachments

Viewed 1095

I'm using RESTeasy 3.x to submit a REST request with an attachment to a third party service. They've asked that the request have the following headers set:

Accept: application/json
Content-Disposition: attachment; filename="attamentFilename"
Content-Type: application/octet-stream

My first attempt was simply to add the headers as I've seen done with Authorization header like this:

protected Response getResponse(final String url, final String filename, final InputStream attachment) {

    ResteasyWebTarget target = resteasyClient.target(url);
    MultipartFormDataOutput output = new MultipartFormDataOutput();
    output.addFormData("attachment", attachment, MediaType.APPLICATION_OCTET_STREAM_TYPE);

    Response response = target.request()
            .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_TYPE)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filename + "\"")
            .post(Entity.entity(output, MediaType.MULTIPART_FORM_DATA));

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    return response;
}

But, when I debugged from the server side the headers weren't being set as expected. I also tried a ClientRequestFilter, but again the headers weren't quite what I needed.

I've managed to get something close to what I need by using addFormData like this:

protected Response getResponse(final String url, final String filename, final InputStream attachment) {

    ResteasyWebTarget target = resteasyClient.target(url);
    MultipartFormDataOutput output = new MultipartFormDataOutput();
    output.addFormData("attachment", attachment, MediaType.APPLICATION_OCTET_STREAM_TYPE, filename);

    Response response = target.request()
            .post(Entity.entity(output, MediaType.MULTIPART_FORM_DATA));

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    return response;
}

This produces two of the three headers I need:

Content-Disposition: form-data; name="attachment"; filename="attamentFilename"
Content-Type: application/octet-stream

I'm assuming MultipartFormDataOutput is discarding the headers I try to set and building its own, and that I can't use the .header method for all types of requests. Does this sound right?

0 Answers
Related