这是我无法压缩响应的代码。我只想压缩特定的端点响应。我用的是Spring Boot和maven。
压缩.java
package com.test.annotations;
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Compress {
}
gzipinterceptor.java文件
import com.test.annotations.Compress;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
@Provider
@Compress
public class GZIPInterceptor implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException {
MultivaluedMap<String,Object> headers = writerInterceptorContext.getHeaders();
headers.add("Content-Encoding", "gzip");
final OutputStream outputStream = writerInterceptorContext.getOutputStream();
writerInterceptorContext.setOutputStream(new GZIPOutputStream(outputStream));
writerInterceptorContext.proceed();
}
}
REST控制器:
@RestController
@RequestMapping(path = "/api/v1")
public class TestCompressController
{
@GetMapping("/compress")
@Compress
public String getLongString()
{
return "Testing with compression.";
}
@GetMapping("/no_compress")
public String getLongString()
{
return "Testing without compression.";
}
}
应用程序属性:
server.compression.enabled=true
server.compression.min-response-size=0
server.compression.mime-types=application/pdf,text/html,application/json
提前谢谢。
暂无答案!
目前还没有任何答案,快来回答吧!