Skip to content

Instantly share code, notes, and snippets.

@rsrini7
Forked from kostanovych/Main.java
Created May 28, 2022 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsrini7/1de15cfb06fff9cf5e01049ff95378a7 to your computer and use it in GitHub Desktop.
Save rsrini7/1de15cfb06fff9cf5e01049ff95378a7 to your computer and use it in GitHub Desktop.
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