我需要向一个包含压缩请求参数的 Web 服务器发送 POST 请求。我正在使用 Apache HttpClient,我已经读到它支持 Gzip 压缩,但我找不到任何关于如何完成我所需的内容的示例。如果有人能提供一些示例,我将不胜感激。
我需要向一个包含压缩请求参数的 Web 服务器发送 POST 请求。我正在使用 Apache HttpClient,我已经读到它支持 Gzip 压缩,但我找不到任何关于如何完成我所需的内容的示例。如果有人能提供一些示例,我将不胜感激。
首先,您需要将该String
转换为压缩的byte[]
或(临时)File
。假设它不是非常大的String
值,可以在可用的JVM内存中安全使用byte[]
:
String foo = "value";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
gzos.write(foo.getBytes("UTF-8"));
}
byte[] fooGzippedBytes = baos.toByteArray();
然后,您可以使用HttpClient将其作为多部分体发送,如下所示:
MultipartEntity entity = new MultipartEntity();
entity.addPart("foo", new InputStreamBody(new ByteArrayInputStream(fooGzippedBytes), "foo.txt"));
HttpPost post = new HttpPost("http://example.com/some");
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
// ...
请注意,HttpClient 4.1支持新的ByteArrayBody
,可以按如下方式使用:
entity.addPart("foo", new ByteArrayBody(fooGzippedBytes, "foo.txt"));
POST
的数据可能非常大,那么如何使用HTTPClient进行操作?我目前在低VM堆(16MB)设备上遇到了“内存不足”的问题。 - HGPB尝试使用GzipCompressingEntity类。如果我要对帖子的主体进行压缩,例如JSON对象,我会按照下面的方式进行:
// json payload
if (jsonBody != null) {
post.setHeader("Content-Type", "application/json");
StringEntity requestEntity = new StringEntity( jsonBody, ContentType.APPLICATION_JSON);
if (gzipBody) {
GzipCompressingEntity gzippedEntity = new GzipCompressingEntity(requestEntity);
post.setEntity(gzippedEntity);
}else {
post.setEntity(requestEntity);
}
}
// add parameters
if (parameters != null && parameters.length > 0){
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
for (int i = 0; i < parameters.length; i++){
urlParameters.add(new BasicNameValuePair(parameters[i][0], parameters[i][1]));
}
post.setEntity(new GzipCompressingEntity(new UrlEncodedFormEntity(urlParameters)));
}
multipart/form-data
部分?你确定目标服务器可以处理吗?服务器到底期望什么?或者服务器代码也完全由你控制吗? - BalusCmultipart/form-data
请求的一部分。服务器期望一个压缩的参数。 - Alex BliskovskyString
吗?是File
吗?等等。 - BalusC