使用附件在RESTeasy请求上设置HTTP标头

时间:2017-11-26 09:28:18

标签: java file-upload resteasy

我使用RESTeasy 3.x提交带有第三方服务附件的REST请求。他们已经要求请求设置了以下标头:

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

我的第一次尝试只是添加标题,因为我已经看到Authorization标题已完成,如下所示:

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

但是,当我从服务器端调试时,标头没有按预期设置。我也尝试了ClientRequestFilter,但标题并不是我所需要的。

我已经设法通过这样使用addFormData获得了我所需要的东西:

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

这会产生我需要的三个标题中的两个:

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

我假设MultipartFormDataOutput正在丢弃我尝试设置和构建自己的标头,并且我无法对所有类型的请求使用.header方法。听起来不错吗?

0 个答案:

没有答案