gpt4 book ai didi

android - 如何压缩 JSONObject 在 Android 中通过 Http 发送?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:18:55 26 4
gpt4 key购买 nike

我正在使用 this example 中的代码从 Android 客户端 向我的网络服务器发送一个 JSONObject .在此处重现代码

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);

我的问题

如何在将 JSONObject 发送到服务器之前对其进行最佳压缩,以及如何在服务器上对其进行解压缩(我正在使用 Java Servlets)?

最佳答案

根据这个http://android-developers.blogspot.com/2011/09/androids-http-clients.html如果您使用 Gingerbread 或更高版本的 HttpURLConnection 会自动添加 gzip 压缩:

In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:

Accept-Encoding: gzip

然后您的网络服务器需要处理 gzip 压缩。

编辑:
Serve Gzipped content with Java Servlets

编辑 2:
使用 DefaultHttpClient 进行 Gzip 压缩 Enabling GZip compression with HttpClient

private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";

final DefaultHttpClient client = new DefaultHttpClient(manager, parameters);

client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) {
// Add header to accept gzip content
if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
}
});

client.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(HttpResponse response, HttpContext context) {
// Inflate any responses compressed with gzip
final HttpEntity entity = response.getEntity();
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
response.setEntity(new InflatingEntity(response.getEntity()));
break;
}
}
}
}
});

编辑 3:
这是关于帖子内容 gzip 的另一个 Stackoverflow 问题 GZip POST request with HTTPClient in Java .您需要在发布数据之前手动对数据进行 gzip 压缩,因为正常的 http/gzip 操作是服务器向客户端发送 gzip 压缩后的内容。

关于android - 如何压缩 JSONObject 在 Android 中通过 Http 发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11402813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com