我正在使用Apache Http Client上传文件。当我将内容长度设置为不正确的文件大小时。
内容长度标头会被文件大小覆盖。 因此导致验收测试失败,因为它允许上传文件,因为内容长度等于文件大小。
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;
}
}
目前,headermap具有必需的标题(Content-Length,Content-Type等)
我可以显式设置Content-Length,而不会在客户端内部覆盖它。任何http客户端都可以。
答案 0 :(得分:0)
任何自尊的HTTP客户端都应该这样做。 HttpURLConnection
当然可以。您的测试无效。内容长度必须与传输的实际字节数相匹配。