【问题标题】:How to receive a GZIP response with RESTClient如何使用 RESTClient 接收 GZIP 响应
【发布时间】:2017-03-17 21:54:49
【问题描述】:

我正在使用仅适用于 GZIP 压缩的服务。我添加了接受标头并且服务可以正常工作,但是 RESTClient 无法正确解析内容。

我的代码:

def client = new RESTClient('https://rest-service-gziped.com')
def postBody = [ somekey: "somevalue" ]
def response = client.post(
    path: "/some-endpoint",
    body: postBody,
    requestContentType : ContentType.JSON,
    headers: ["Accept-Encoding": "gzip"]
)

错误信息是

Mar 17, 2017 5:48:03 PM groovyx.net.http.RESTClient handleResponse
WARNING: Error parsing 'application/json; charset=utf-8' response
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

【问题讨论】:

    标签: java groovy httpbuilder


    【解决方案1】:

    只需在 RESTClient 实例化后添加以下内容

    client.setContentEncoding(ContentEncoding.Type.GZIP, ContentEncoding.Type.DEFLATE)

    【讨论】:

      【解决方案2】:

      如果您使用的是微配置文件 RestClientBuilder:

      RestClientBuilder.newBuilder()
                      .baseUri(java.net.URI.create(baseUri))
                      .register(AcceptEncodingGZIPFilter.class)
                      .register(GZIPDecodingInterceptor.class)
                      .register(GZIPEncodingInterceptor.class)
                      .build(SomeInterface.class);
      

      要压缩post请求的内容,接口“SomeInterface”的方法中的参数必须用@GZIP注解:

      @GZIP
      @POST
      @Consumes(MediaType.APPLICATION_JSON)
      @Produces(MediaType.APPLICATION_JSON)
      @Path("/test/data")
      public ReturnObject PostRequest(@GZIP SomeData data)
      

      方法级别(或接口级别)的@GZIP 注解用于接受压缩响应。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        • 1970-01-01
        • 2014-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-16
        相关资源
        最近更新 更多