Java 中使用 HTTPClient 的 GZip POST 请求
我需要向 Web 服务器发送 POST 请求,其中包含压缩的请求参数。我正在使用 Apache HttpClient,并且我读到它支持开箱即用的 Gzip,但我找不到任何有关如何执行我需要的操作的示例。如果有人可以发布一些这方面的例子,我将不胜感激。
I need to send a POST request to a web server which includes a gzipped request parameter. I'm using Apache HttpClient and I've read that it supports Gzip out of the box, but I can't find any examples of how to do what I need. I'd appreciate it if anyone could post some examples of this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要首先将该
String
转换为 gzippedbyte[]
或(temp)File
。假设它不是一个非常大的String
值,因此byte[]
对于可用的 JVM 内存来说足够安全:然后,您可以使用以下命令将其作为多部分主体发送 : HttpClient如下:
注意HttpClient 4.1支持新的
ByteArrayBody< /code>
可以按如下方式使用:
You need to turn that
String
into a gzippedbyte[]
or (temp)File
first. Let's assume that it's not an extraordinary largeString
value so that abyte[]
is safe enough for the available JVM memory:Then, you can send it as a multipart body using HttpClient as follows:
Note that HttpClient 4.1 supports the new
ByteArrayBody
which can be used as follows:尝试 GzipCompressingEntity 类。如果我要压缩帖子的正文,例如 JSON 对象,我会去:
尚未测试,但我假设要添加参数,您会这样做:
Try the GzipCompressingEntity class. If I'm zipping the body of a post e.g. for a JSON object I would go:
Haven't tested but I assume for adding parameters you'd do: