1

I am using Apache Http Client to upload a file. When I set the content-length to incorrect file-size.

The content length header gets overridden by the file size. Thus causing acceptance test to fail as it allows to upload the file because the content-length is equal to file-size.

public class RestClient {
    Client client = null;

    public RestClient() {
        client = Client.create();
        //client.addFilter(new LoggingFilter(System.out));
    }

    public ClientResponse postData(String url, Map headerMap) throws IOException {
        ClientResponse response = null;

        try {
            WebResource webResource = client.resource(url);
            Builder requestBuilder = webResource.getRequestBuilder();
            Iterator it = headerMap.entrySet().iterator();

            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry) it.next();
                requestBuilder = requestBuilder.header(pair.getKey().toString(), pair.getValue());
            }

            if (headerMap.get("filename") != null) {
                ClassLoader cl = getClass().getClassLoader();
                InputStream fileInStream = cl.getResourceAsStream(headerMap.get("filename").toString());
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                requestBuilder = requestBuilder.entity(fileInStream);
            }

            response = requestBuilder.header("Expect", new String("100-continue"))
                    .post(ClientResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    public ClientResponse getData(String url) {
        ClientResponse response = null;

        WebResource webResource = client.resource(url);
        response = webResource.get(ClientResponse.class);

        return response;
    }
}

Currently headermap has required headers (Content-Length,Content-Type etc.)

Can I set Content-Length explicitly without the client internally overriding it. Any http client is ok.

1 Answers1

0

Any self-respecting HTTP client should do the same. HttpURLConnection certainly does. Your test is invalid. The content-length must match the actual number of bytes transmitted.

user207421
  • 305,947
  • 44
  • 307
  • 483