简体   繁体   中英

Jersey Client doesn't set Content-Length

I am using dropwizard for writing a webapp and also using Jersey Client as mentioned at http://dropwizard.codahale.com/manual/client/#man-client-jersey

But it seems that whenever i try to do a post using the jersey client the remote webservice complains that Content-Length header is missing and fails.

public JobResponse createJob(JobRequest job) {
        return jerseyClient.resource(URI.create(JOBS_URL))
                .type(MediaType.APPLICATION_JSON_TYPE)
                .header("Api-Key", job.getApiKey())
                .post(JobResponse.class, job);
    }

I have confirmed that the request does not contain the header and despite my best efforts I haven't been able to figure out why this is happening. Does anyone know if there is something that I am missing?

PS: The service that i am trying to hit is https://app.zencoder.com/docs/api/jobs/create

This is known "issue" and actually intended behavior.

Problem here is that entity is processed AFTER headers are written out to "the wire", thus Content-Length header value is not know when headers are serialized. If you need to have it, you have several options (with various complexity):

  1. serialize entity by yourself; if you provide entity as string (or byte[]), Content-Length should be set.

  2. create your own MessageBodyWriter, which would compute size of entity in getSize() method call.

there might be some other way how to do it, but I can't think of another right now.. hope it helps.

I was facing the same problem and the answer from Pavel didn't work out for me (I was using a FormMutiPart object).

I was using ApacheHttpClient4 instead of the regular com.sun.jersey.api.client.Client . Changing back to the Jersey Client, the Content-Lenght is calculated (at least in the case of FormMultiPart entity).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM