自動解凍の場合
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class GzipClientAuto {
public static void main(String[] args) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet request = new HttpGet("http://localhost:8080/gzip");
request.addHeader("Accept-Encoding", "gzip");
try (CloseableHttpResponse response = client.execute(request)) {
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity, "UTF-8");
System.out.println("Response: " + body);
}
}
}
}
手動で GZIP 解凍する場合
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
public class GzipClientManual {
public static void main(String[] args) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet request = new HttpGet("http://localhost:8080/gzip");
request.addHeader("Accept-Encoding", "gzip");
try (CloseableHttpResponse response = client.execute(request)) {
HttpEntity entity = response.getEntity();
String contentEncoding = response.getFirstHeader("Content-Encoding") != null
? response.getFirstHeader("Content-Encoding").getValue()
: "";
InputStream inputStream = entity.getContent();
if ("gzip".equalsIgnoreCase(contentEncoding)) {
inputStream = new GZIPInputStream(inputStream);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Response: " + line);
}
}
}
}
}
まとめ
解凍方法 | 特徴 |
---|---|
自動(EntityUtils.toString() ) |
一般的で簡単。Content-Encoding を自動処理。 |
手動(GZIPInputStream ) |
カスタム処理や細かい制御が必要な場合に適用。 |