retrofit2.Call类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(10.1k)|赞(0)|评价(0)|浏览(244)

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

Call介绍

[英]An invocation of a Retrofit method that sends a request to a webserver and returns a response. Each call yields its own HTTP request and response pair. Use #clone to make multiple calls with the same parameters to the same webserver; this may be used to implement polling or to retry a failed call.

Calls may be executed synchronously with #execute, or asynchronously with #enqueue. In either case the call can be canceled at any time with #cancel. A call that is busy writing its request or reading its response may receive a IOException; this is working as designed.
[中]对改造方法的调用,该方法向Web服务器发送请求并返回响应。每个调用生成自己的HTTP请求和响应对。使用#clone对同一Web服务器进行多个参数相同的调用;这可用于实现轮询或重试失败的呼叫。
调用可以与#execute同步执行,也可以与#enqueue异步执行。无论哪种情况,都可以随时使用#cancel取消通话。忙于写请求或读取响应的呼叫可能会收到IOException;这是工作的设计。

代码示例

代码示例来源:origin: square/retrofit

@Override public ListenableFuture<Response<R>> adapt(final Call<R> call) {
  return new AbstractFuture<Response<R>>() {
   {
    call.enqueue(new Callback<R>() {
     @Override public void onResponse(Call<R> call, Response<R> response) {
      set(response);
     }
     @Override public void onFailure(Call<R> call, Throwable t) {
      setException(t);
     }
    });
   }
   @Override protected void interruptTask() {
    call.cancel();
   }
  };
 }
}

代码示例来源:origin: square/retrofit

private static void printContributors(GitHub gitHub, String owner, String repo)
   throws IOException {
  System.out.println(String.format("== Contributors for %s/%s ==", owner, repo));
  Call<List<Contributor>> contributors = gitHub.contributors(owner, repo);
  for (Contributor contributor : contributors.execute().body()) {
   System.out.println(contributor.login + " (" + contributor.contributions + ")");
  }
  System.out.println();
 }
}

代码示例来源:origin: square/retrofit

@Override protected void interruptTask() {
  call.cancel();
 }
};

代码示例来源:origin: Graylog2/graylog2-server

final Call<RemoteCallResponseType> call = fn.apply(r);
try {
  final Response<RemoteCallResponseType> response = call.execute();
  if (response.isSuccessful()) {
    return Optional.of(transformer.apply(response.body()));
  } else {
    LOG.warn("Unable to call {} on node <{}>, result: {}", call.request().url(), node, response.message());
    return Optional.<FinalResponseType>empty();
  LOG.warn("Unable to call {} on node <{}>", call.request().url(), node, e);
  return Optional.<FinalResponseType>empty();

代码示例来源:origin: square/retrofit

@Override public void onResponse(Call<Page> call, Response<Page> response) {
 if (!response.isSuccessful()) {
  System.out.println(call.request().url() + ": failed: " + response.code());
  return;
 }
 // Print this page's URL and title.
 Page page = response.body();
 HttpUrl base = response.raw().request().url();
 System.out.println(base + ": " + page.title);
 // Enqueue its links for visiting.
 for (String link : page.links) {
  HttpUrl linkUrl = base.resolve(link);
  if (linkUrl != null && fetchedUrls.add(linkUrl)) {
   crawlPage(linkUrl);
  }
 }
}

代码示例来源:origin: Graylog2/graylog2-server

@GET
@Path("{jobId}")
@Timed
@ApiOperation(value = "Get job with the given ID")
@Produces(MediaType.APPLICATION_JSON)
public SystemJobSummary getJob(@ApiParam(name = "jobId", required = true) @PathParam("jobId") String jobId) throws IOException {
  for (Map.Entry<String, Node> entry : nodeService.allActive().entrySet()) {
    final RemoteSystemJobResource remoteSystemJobResource = remoteInterfaceProvider.get(entry.getValue(), this.authenticationToken, RemoteSystemJobResource.class);
    try {
      final Response<SystemJobSummary> response = remoteSystemJobResource.get(jobId).execute();
      if (response.isSuccessful()) {
        // Return early because there can be only one job with the same ID in the cluster.
        return response.body();
      }
    } catch (IOException e) {
      LOG.warn("Unable to fetch system jobs from node {}:", entry.getKey(), e);
    }
  }
  throw new NotFoundException("System job with id " + jobId + " not found!");
}

代码示例来源:origin: square/retrofit

public static void main(String... args) throws IOException {
  HostSelectionInterceptor hostSelectionInterceptor = new HostSelectionInterceptor();

  OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(hostSelectionInterceptor)
    .build();

  Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://www.github.com/")
    .callFactory(okHttpClient)
    .build();

  Pop pop = retrofit.create(Pop.class);

  Response<ResponseBody> response1 = pop.robots().execute();
  System.out.println("Response from: " + response1.raw().request().url());
  System.out.println(response1.body().string());

  hostSelectionInterceptor.setHost("www.pepsi.com");

  Response<ResponseBody> response2 = pop.robots().execute();
  System.out.println("Response from: " + response2.raw().request().url());
  System.out.println(response2.body().string());
 }
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void passThroughCallsToDecoratedObject() throws IOException {
  final Call<String> call = mock(StringCall.class);
  final Call<String> decorated = new DecoratedCall<>(call);
  decorated.cancel();
  Mockito.verify(call).cancel();
  decorated.enqueue(null);
  Mockito.verify(call).enqueue(any());
  decorated.isExecuted();
  Mockito.verify(call).isExecuted();
  decorated.isCanceled();
  Mockito.verify(call).isCanceled();
  decorated.clone();
  Mockito.verify(call).clone();
  decorated.request();
  Mockito.verify(call).request();
  decorated.execute();
  Mockito.verify(call).execute();
}

代码示例来源:origin: square/retrofit

@Override public Response<T> execute() throws IOException {
 return delegate.execute();
}

代码示例来源:origin: Graylog2/graylog2-server

@POST
  @Timed
  @ApiOperation(value = "Resume message processing on node")
  @Path("resume")
  @NoAuditEvent("proxy resource, audit event will be emitted on target node")
  public void resume(@ApiParam(name = "nodeId", value = "The id of the node where processing will be resumed.", required = true)
            @PathParam("nodeId") String nodeId) throws IOException, NodeNotFoundException {
    final Response response = this.getRemoteSystemProcessingResource(nodeId).resume().execute();
    if (!response.isSuccessful()) {
      LOG.warn("Unable to resume message processing on node {}: {}", nodeId, response.message());
      throw new WebApplicationException(response.message(), BAD_GATEWAY);
    }
  }
}

代码示例来源:origin: Graylog2/graylog2-server

@POST
  @Timed
  @ApiOperation(value = "Shutdown node gracefully.",
      notes = "Attempts to process all buffered and cached messages before exiting, " +
          "shuts down inputs first to make sure that no new messages are accepted.")
  @AuditEvent(type = AuditEventTypes.NODE_SHUTDOWN_INITIATE)
  public void shutdown(@ApiParam(name = "nodeId", value = "The id of the node to shutdown.", required = true)
             @PathParam("nodeId") String nodeId) throws IOException, NodeNotFoundException {
    final Node targetNode = nodeService.byNodeId(nodeId);

    RemoteSystemShutdownResource remoteSystemShutdownResource = remoteInterfaceProvider.get(targetNode,
        this.authenticationToken,
        RemoteSystemShutdownResource.class);
    final Response response = remoteSystemShutdownResource.shutdown().execute();
    if (response.code() != ACCEPTED.getStatusCode()) {
      LOG.warn("Unable send shut down signal to node {}: {}", nodeId, response.message());
      throw new WebApplicationException(response.message(), BAD_GATEWAY);
    }
  }
}

代码示例来源:origin: line/armeria

@Test
public void pojo_returnCallCancelBeforeEnqueue() throws Exception {
  final CountDownLatch countDownLatch = new CountDownLatch(1);
  final Call<Pojo> pojoCall = service.pojoReturnCall();
  pojoCall.cancel();
  pojoCall.enqueue(new Callback<Pojo>() {
    @Override
    public void onResponse(Call<Pojo> call, Response<Pojo> response) {
    }
    @Override
    public void onFailure(Call<Pojo> call, Throwable t) {
      countDownLatch.countDown();
    }
  });
  assertThat(countDownLatch.await(3, TimeUnit.SECONDS)).isTrue();
}

代码示例来源:origin: square/retrofit

@Override protected void subscribeActual(Observer<? super Response<T>> observer) {
 // Since Call is a one-shot type, clone it for each new observer.
 Call<T> call = originalCall.clone();
 CallCallback<T> callback = new CallCallback<>(call, observer);
 observer.onSubscribe(callback);
 if (!callback.isDisposed()) {
  call.enqueue(callback);
 }
}

代码示例来源:origin: square/retrofit

Service service = retrofit.create(Service.class);
Response<User> response = service.getUser().execute();
  retrofit.responseBodyConverter(Error.class, new Annotation[0]);
Error error = errorConverter.convert(response.errorBody());
System.out.println("ERROR: " + error.message);

代码示例来源:origin: resilience4j/resilience4j

@Test
public void decorateUnsuccessfulCall() throws Exception {
  stubFor(get(urlPathEqualTo("/greeting"))
      .willReturn(aResponse()
          .withStatus(500)
          .withHeader("Content-Type", "text/plain")));
  final Response<String> response = service.greeting().execute();
  assertThat(response.code())
      .describedAs("Response code")
      .isEqualTo(500);
  final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
}

代码示例来源:origin: square/retrofit

@Override public void call(Subscriber<? super Response<T>> subscriber) {
  // Since Call is a one-shot type, clone it for each new subscriber.
  Call<T> call = originalCall.clone();
  CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber);
  subscriber.add(arbiter);
  subscriber.setProducer(arbiter);

  Response<T> response;
  try {
   response = call.execute();
  } catch (Throwable t) {
   Exceptions.throwIfFatal(t);
   arbiter.emitError(t);
   return;
  }
  arbiter.emitResponse(response);
 }
}

代码示例来源:origin: TakWolf/CNode-Material-Design

@Override
public void onCancel(DialogInterface dialog) {
  if (!call.isCanceled()) {
    call.cancel();
  }
}

代码示例来源:origin: square/retrofit

@Override public Request request() {
  return delegate.request();
 }
}

代码示例来源:origin: resilience4j/resilience4j

@Override
public Call<T> clone() {
  return call.clone();
}

代码示例来源:origin: Graylog2/graylog2-server

@GET
@Timed
@Path("/names")
@ApiOperation(value = "Get all metrics keys/names from node")
@RequiresPermissions(RestPermissions.METRICS_ALLKEYS)
public MetricNamesResponse metricNames(@ApiParam(name = "nodeId", value = "The id of the node whose metrics we want.", required = true)
                    @PathParam("nodeId") String nodeId) throws IOException, NodeNotFoundException {
  final Response<MetricNamesResponse> result = getResourceForNode(nodeId).metricNames().execute();
  if (result.isSuccessful()) {
    return result.body();
  } else {
    throw new WebApplicationException(result.message(), BAD_GATEWAY);
  }
}

相关文章