Skip to content

Instantly share code, notes, and snippets.

@berserkk
Last active Jul 31, 2018
Embed
What would you like to do?
Simple example of compressing HTTP request via gzip with using Spring RestTemplate
group 'com.github.berserkk'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: '1.5.4.RELEASE'
compile group: 'org.springframework', name: 'spring-web', version: '4.3.9.RELEASE'
}
<?php
if (!function_exists('gzdecode')) {
function gzdecode($data) {
return gzinflate(substr($data, 10, -8));
}
}
echo gzdecode(file_get_contents('php://input'));
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.HttpMessageConverterExtractor;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;
public class Main {
public static void main(String args[]) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
GZIPOutputStream gzipOutputStream;
try {
gzipOutputStream = new GZIPOutputStream(request.getBody());
} catch (IOException ignored) {
return;
}
request.getHeaders().add("Content-Type", "application/octet-stream");
request.getHeaders().add("Content-Encoding", "gzip");
try {
String data = "Test data.";
gzipOutputStream.write(data.getBytes(StandardCharsets.UTF_8));
gzipOutputStream.flush(); // Optional in this example.
gzipOutputStream.finish();
} catch (IOException ignored) {
}
}
};
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
ResponseExtractor<String> responseExtractor = new HttpMessageConverterExtractor<>(String.class,
restTemplate.getMessageConverters());
String response = restTemplate.execute("http://localhost:8080/gzip.php", HttpMethod.POST, requestCallback,
responseExtractor);
System.out.println(response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment