javax.ws.rs.core.Response.close()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(14.1k)|赞(0)|评价(0)|浏览(230)

本文整理了Java中javax.ws.rs.core.Response.close方法的一些代码示例,展示了Response.close的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Response.close方法的具体详情如下:
包路径:javax.ws.rs.core.Response
类名称:Response
方法名:close

Response.close介绍

[英]Close the underlying message entity input stream (if available and open) as well as releases any other resources associated with the response (e.g. #bufferEntity()).

This operation is idempotent, i.e. it can be invoked multiple times with the same effect which also means that calling the close() method on an already closed message instance is legal and has no further effect.

The close() method should be invoked on all instances that contain an un-consumed entity input stream to ensure the resources associated with the instance are properly cleaned-up and prevent potential memory leaks. This is typical for client-side scenarios where application layer code processes only the response headers and ignores the response entity.

Any attempts to manipulate (read, get, buffer) a message entity on a closed response will result in an IllegalStateException being thrown.
[中]关闭底层消息实体输入流(如果可用并打开),并释放与响应相关的任何其他资源(例如#bufferEntity())。
这个操作是幂等的,也就是说,它可以被多次调用,具有相同的效果,这也意味着在已经关闭的消息实例上调用close()方法是合法的,没有进一步的效果。
应该在包含未使用的实体输入流的所有实例上调用close()方法,以确保与实例关联的资源得到正确清理,并防止潜在的内存泄漏。这是典型的客户端场景,其中应用层代码只处理响应头,而忽略响应实体。
在关闭的响应上操纵(读取、获取、缓冲)消息实体的任何尝试都将导致抛出非法状态异常。

代码示例

代码示例来源:origin: Netflix/eureka

@Override
public EurekaHttpResponse<Void> statusUpdate(String asgName, ASGStatus newStatus) {
  Response response = null;
  try {
    String urlPath = "asg/" + asgName + "/status";
    response = jerseyClient.target(serviceUrl)
        .path(urlPath)
        .queryParam("value", newStatus.name())
        .request()
        .header(PeerEurekaNode.HEADER_REPLICATION, "true")
        .put(Entity.text(""));
    return EurekaHttpResponse.status(response.getStatus());
  } finally {
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: Netflix/eureka

@Override
public EurekaHttpResponse<ReplicationListResponse> submitBatchUpdates(ReplicationList replicationList) {
  Response response = null;
  try {
    response = jerseyClient.target(serviceUrl)
        .path(PeerEurekaNode.BATCH_URL_PATH)
        .request(MediaType.APPLICATION_JSON_TYPE)
        .post(Entity.json(replicationList));
    if (!isSuccess(response.getStatus())) {
      return anEurekaHttpResponse(response.getStatus(), ReplicationListResponse.class).build();
    }
    ReplicationListResponse batchResponse = response.readEntity(ReplicationListResponse.class);
    return anEurekaHttpResponse(response.getStatus(), batchResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
  } finally {
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: spotify/docker-client

private void tailResponse(final String method, final Response response,
             final ProgressHandler handler, final WebTarget resource)
   throws DockerException, InterruptedException {
 final ExecutorService executor = Executors.newSingleThreadExecutor();
 try {
  final ProgressStream stream = response.readEntity(ProgressStream.class);
  final Future<?> future = executor.submit(
      new ResponseTailReader(stream, handler, method, resource));
  future.get();
 } catch (ExecutionException e) {
  final Throwable cause = e.getCause();
  if (cause instanceof DockerException) {
   throw (DockerException)cause;
  } else {
   throw new DockerException(cause);
  }
 } finally {
  executor.shutdownNow();
  try {
   response.close();
  } catch (ProcessingException e) {
   // ignore, thrown by jnr-unixsocket when httpcomponent try to read after close
   // the socket is closed before this exception
  }
 }
}

代码示例来源:origin: GluuFederation/oxTrust

public String add(T requestEntity) throws OxTrustAPIException {
  WebTarget resource=webTarget;
  System.out.println("Final Url:" + resource.getUri().toString());
  Response response = resource.request().post(Entity.entity(requestEntity, MediaType.APPLICATION_JSON));
  if (response.getStatus() != HTTP_OK) {
    System.out.println("Error:" + response.getStatus());
    throw new OxTrustAPIException("Response error. HTTP code: " + response.getStatus() + ", reason phrase: "
        + response.getStatusInfo().getReasonPhrase(), response.getStatus());
  }
  response.close();
  return response.readEntity(String.class);
}

代码示例来源:origin: stackoverflow.com

Client client = ClientFactory.newClient();
WebTarget target = client.target("http://localhost/test");
Response response = target.request().get();
if ( response.getStatusCode() != Response.Status.OK.getStatusCode() ) {
  System.out.println( response.readEntity(String.class) );
  return null;
}
String value = response.readEntity(String.class);
response.close();

代码示例来源:origin: Netflix/eureka

private EurekaHttpResponse<InstanceInfo> getInstanceInternal(String urlPath) {
  Response response = null;
  try {
    Builder requestBuilder = jerseyClient.target(serviceUrl).path(urlPath).request();
    addExtraProperties(requestBuilder);
    addExtraHeaders(requestBuilder);
    response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get();
    InstanceInfo infoFromPeer = null;
    if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) {
      infoFromPeer = response.readEntity(InstanceInfo.class);
    }
    return anEurekaHttpResponse(response.getStatus(), infoFromPeer).headers(headersOf(response)).build();
  } finally {
    if (logger.isDebugEnabled()) {
      logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
    }
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: Netflix/eureka

@Override
public EurekaHttpResponse<Void> cancel(String appName, String id) {
  String urlPath = "apps/" + appName + '/' + id;
  Response response = null;
  try {
    Builder resourceBuilder = jerseyClient.target(serviceUrl).path(urlPath).request();
    addExtraProperties(resourceBuilder);
    addExtraHeaders(resourceBuilder);
    response = resourceBuilder.delete();
    return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
  } finally {
    if (logger.isDebugEnabled()) {
      logger.debug("Jersey2 HTTP DELETE {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
    }
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: stackoverflow.com

final String url = "http://stackoverflow.com/questions/27160440/" +
                  "jersey-client-api-vs-jersey-test-framework";
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().accept(MediaType..get();
String html  = response.readEntity(String.class);
System.out.println(html);
response.close();

代码示例来源:origin: Netflix/eureka

@Override
public EurekaHttpResponse<Application> getApplication(String appName) {
  String urlPath = "apps/" + appName;
  Response response = null;
  try {
    Builder requestBuilder = jerseyClient.target(serviceUrl).path(urlPath).request();
    addExtraProperties(requestBuilder);
    addExtraHeaders(requestBuilder);
    response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get();
    Application application = null;
    if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) {
      application = response.readEntity(Application.class);
    }
    return anEurekaHttpResponse(response.getStatus(), application).headers(headersOf(response)).build();
  } finally {
    if (logger.isDebugEnabled()) {
      logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
    }
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: Netflix/eureka

@Override
public EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info) {
  String urlPath = "apps/" + appName + '/' + id + "/status";
  Response response = null;
  try {
    Builder requestBuilder = jerseyClient.target(serviceUrl)
        .path(urlPath)
        .queryParam("value", newStatus.name())
        .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString())
        .request();
    addExtraProperties(requestBuilder);
    addExtraHeaders(requestBuilder);
    response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); // Jersey2 refuses to handle PUT with no body
    return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
  } finally {
    if (logger.isDebugEnabled()) {
      logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
    }
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: stackoverflow.com

@Path("/date")
public class DateResource {
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  public Response postPerson(Person person) {
    return Response.ok(DateTimeFormatter.ISO_DATE.format(
              person.getBirthDate())).build();
  }
}

@Test
public void testResteasy() throws Exception {
  WebTarget target = client.target(
      TestPortProvider.generateURL(BASE_URI)).path("date");
  String person = "{\"birthDate\":\"2015-01-04\"}";
  Response response = target.request().post(Entity.json(person));
  System.out.println(response.readEntity(String.class));
  response.close();
}

代码示例来源:origin: stackoverflow.com

System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
response.close();

代码示例来源:origin: Netflix/eureka

@Override
public EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info) {
  String urlPath = "apps/" + appName + '/' + id + "/status";
  Response response = null;
  try {
    Builder requestBuilder = jerseyClient.target(serviceUrl)
        .path(urlPath)
        .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString())
        .request();
    addExtraProperties(requestBuilder);
    addExtraHeaders(requestBuilder);
    response = requestBuilder.delete();
    return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
  } finally {
    if (logger.isDebugEnabled()) {
      logger.debug("Jersey2 HTTP DELETE {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
    }
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: stackoverflow.com

@Test
public void testGetIt() {
  // Get all list
  WidgetList list = target.path("widgets")
              .request().get(WidgetList.class);
  System.out.println("===== Response from GET =====");
  for (Widget widget: list.getWidgetList()) {
    System.out.println("id: " + widget.getId() 
             + ", name: " + widget.getName());
  }

  // Post one 
  Widget widget = Widget.newBuilder().setId("10")
             .setName("widget 10").build();
  Response responseFromPost = target.path("widgets").request()
      .post(Entity.entity(widget, "application/protobuf"));
  System.out.println("===== Response from POST =====");
  System.out.println(responseFromPost.readEntity(String.class));
  responseFromPost.close();
}

代码示例来源:origin: Netflix/eureka

private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath, String[] regions) {
  Response response = null;
  try {
    WebTarget webTarget = jerseyClient.target(serviceUrl).path(urlPath);
    if (regions != null && regions.length > 0) {
      webTarget = webTarget.queryParam("regions", StringUtil.join(regions));
    }
    Builder requestBuilder = webTarget.request();
    addExtraProperties(requestBuilder);
    addExtraHeaders(requestBuilder);
    response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).get();
    Applications applications = null;
    if (response.getStatus() == Status.OK.getStatusCode() && response.hasEntity()) {
      applications = response.readEntity(Applications.class);
    }
    return anEurekaHttpResponse(response.getStatus(), applications).headers(headersOf(response)).build();
  } finally {
    if (logger.isDebugEnabled()) {
      logger.debug("Jersey2 HTTP GET {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus());
    }
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: Netflix/eureka

@Override
public EurekaHttpResponse<Void> register(InstanceInfo info) {
  String urlPath = "apps/" + info.getAppName();
  Response response = null;
  try {
    Builder resourceBuilder = jerseyClient.target(serviceUrl).path(urlPath).request();
    addExtraProperties(resourceBuilder);
    addExtraHeaders(resourceBuilder);
    response = resourceBuilder
        .accept(MediaType.APPLICATION_JSON)
        .acceptEncoding("gzip")
        .post(Entity.json(info));
    return anEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
  } finally {
    if (logger.isDebugEnabled()) {
      logger.debug("Jersey2 HTTP POST {}/{} with instance {}; statusCode={}", serviceUrl, urlPath, info.getId(),
          response == null ? "N/A" : response.getStatus());
    }
    if (response != null) {
      response.close();
    }
  }
}

代码示例来源:origin: stackoverflow.com

public void test() {
  Response response = target("hello").request().get();
  String hello = response.readEntity(String.class);
  assertEquals("Hello World!", hello);
  response.close();

代码示例来源:origin: Netflix/eureka

response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); // Jersey2 refuses to handle PUT with no body
  InstanceInfo infoFromPeer = null;
  if (response.getStatus() == Status.CONFLICT.getStatusCode() && response.hasEntity()) {
    infoFromPeer = response.readEntity(InstanceInfo.class);
  return anEurekaHttpResponse(response.getStatus(), infoFromPeer).type(MediaType.APPLICATION_JSON_TYPE).build();
} finally {
  if (logger.isDebugEnabled()) {
    logger.debug("[heartbeat] Jersey HTTP PUT {}; statusCode={}", urlPath, response == null ? "N/A" : response.getStatus());
    response.close();

代码示例来源:origin: confluentinc/ksql

private <T> RestResponse<T> postRequest(
  final String path,
  final Object jsonEntity,
  final Optional<Integer> readTimeoutMs,
  final boolean closeResponse,
  final Function<Response, T> mapper) {
 Response response = null;
 try {
  final WebTarget target = client.target(serverAddress)
    .path(path);
  readTimeoutMs.ifPresent(timeout -> target.property(ClientProperties.READ_TIMEOUT, timeout));
  response = target
    .request(MediaType.APPLICATION_JSON_TYPE)
    .post(Entity.json(jsonEntity));
  return response.getStatus() == Response.Status.OK.getStatusCode()
    ? RestResponse.successful(mapper.apply(response))
    : createErrorResponse(path, response);
 } catch (final ProcessingException e) {
  if (shouldRetry(readTimeoutMs, e)) {
   return postRequest(path, jsonEntity, calcReadTimeout(readTimeoutMs), closeResponse, mapper);
  }
  throw new KsqlRestClientException("Error issuing POST to KSQL server. path:" + path, e);
 } catch (final Exception e) {
  throw new KsqlRestClientException("Error issuing POST to KSQL server. path:" + path, e);
 } finally {
  if (response != null && closeResponse) {
   response.close();
  }
 }
}

代码示例来源:origin: stackoverflow.com

WebTarget target = client.target(BASE_URI);
Response response = target.path("hello").request().get();
String hello = response.readEntity(String.class);
assertEquals("Hello World!", hello);
response.close();

相关文章