import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.commons.io.IOUtils;
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.HttpClientBuilder;
import org.apache.http.impl.client.cache.CacheConfig;
import org.apache.http.impl.client.cache.CachingHttpClientBuilder;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
public class GZipCachingHttpClientBuilderTest {
private static final String TEST_BODY = "Sometext";
@Rule
public WireMockRule wireMockRule = new WireMockRule(0);
@Test
public void testGzipError() throws Exception {
stubFor(get(urlEqualTo("/my/resource"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Cache-Control", "public")
.withHeader("ETag", "123")
.withBody(TEST_BODY)
));
stubFor(get(urlEqualTo("/my/resource"))
.withHeader("If-None-Match", equalTo("123"))
.willReturn(aResponse()
.withHeader("Content-Encoding", "gzip")
.withStatus(304)
));
CacheConfig.Builder cfgBuilder = CacheConfig.custom();
CacheConfig cfg = cfgBuilder.setMaxCacheEntries(1024).build();
HttpClientBuilder bld = CachingHttpClientBuilder.create().setCacheConfig(cfg);
CloseableHttpClient client = bld.build();
executeRequest(client);
executeRequest(client); }
private void executeRequest(CloseableHttpClient client) throws IOException {
int port = wireMockRule.port();
CloseableHttpResponse resp = client.execute(new HttpGet("http:+port+"/my/resource"));
Assert.assertEquals(TEST_BODY, IOUtils.toString(resp.getEntity().getContent()));
}
}