javax.ws.rs.client.Client.target()方法的使用及代码示例

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

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

Client.target介绍

[英]Build a new web resource target.
[中]构建新的web资源目标。

代码示例

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

private WebTarget resource() {
 final WebTarget target = client.target(uri);
 if (!isNullOrEmpty(apiVersion)) {
  return target.path(apiVersion);
 }
 return target;
}

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

@Benchmark
public Response get() throws Exception {
  return client.target("foo").request().get();
}

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

public static void generateFile(final String resourceRelativeUrl, final int minimalSize, final String fileName)
    throws IOException {
  LOG.info("Generating file " + fileName);
  final Client client = ClientBuilder.newClient();
  final WebTarget target = client.target(baseUri).path("generate").path(resourceRelativeUrl);
  final File file = new File(fileName);
  final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
      new FileOutputStream(file), Charset.forName("UTF-8")));
  int actualSize = 0;
  while (actualSize < minimalSize) {
    final String response = target.request().get(String.class);
    writer.write(response + ENTITY_SEPARATOR);
    actualSize += response.length();
  }
  writer.flush();
  writer.close();
}

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

private <T> RestResponse<T> getRequest(final String path, final Class<T> type) {
 try (Response response = client.target(serverAddress)
   .path(path)
   .request(MediaType.APPLICATION_JSON_TYPE)
   .get()) {
  return response.getStatus() == Response.Status.OK.getStatusCode()
    ? RestResponse.successful(response.readEntity(type))
    : createErrorResponse(path, response);
 } catch (final Exception e) {
  throw new KsqlRestClientException("Error issuing GET to KSQL server. path:" + path, e);
 }
}

代码示例来源:origin: apache/nifi

public void get(final GetStatusConfig config) {
  final SSLContext sslContext = config.getSslContext();
  final ClientBuilder clientBuilder = ClientBuilder.newBuilder();
  if (sslContext != null) {
    clientBuilder.sslContext(sslContext);
  }
  final ClientConfig clientConfig = new ClientConfig();
  clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 10000);
  clientConfig.property(ClientProperties.READ_TIMEOUT, 10000);
  clientBuilder.withConfig(clientConfig);
  final Client client = clientBuilder.build();
  final WebTarget target = client.target(config.getUrl());
  final Response response = target.request().get();
  System.out.println("Response Code - " + response.getStatus());
}

代码示例来源: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: 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();

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

public String start() {
  final Response response = addProperties(client.target(requestTokenUri).request())
      .post(null);
  if (response.getStatus() != 200) {
    throw new RuntimeException(LocalizationMessages.ERROR_REQUEST_REQUEST_TOKEN(response.getStatus()));
  }
  final MultivaluedMap<String, String> formParams = response.readEntity(Form.class).asMap();
  parameters.token(formParams.getFirst(OAuth1Parameters.TOKEN));
  secrets.tokenSecret(formParams.getFirst(OAuth1Parameters.TOKEN_SECRET));
  return UriBuilder.fromUri(authorizationUri).queryParam(OAuth1Parameters.TOKEN, parameters.getToken())
      .build().toString();
}

代码示例来源:origin: apache/usergrid

@Override
Map<String, Object> userFromResource( String externalToken ) {
  return client.target( apiUrl )
    .queryParam( "access_token", externalToken )
    .request()
      .accept( MediaType.APPLICATION_JSON )
      .get( Map.class );
}

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

@Override
public String ping() throws DockerException, InterruptedException {
 final WebTarget resource = client.target(uri).path("_ping");
 return request(GET, String.class, resource, resource.request());
}

代码示例来源:origin: apache/hbase

private void doRoleCommand(String serviceName, String roleName, RoleCommand roleCommand) {
 URI uri = UriBuilder.fromUri(serverHostname)
   .path("api")
   .path(API_VERSION)
   .path("clusters")
   .path(clusterName)
   .path("services")
   .path(serviceName)
   .path("roleCommands")
   .path(roleCommand.toString())
   .build();
 String body = "{ \"items\": [ \"" + roleName + "\" ] }";
 LOG.info("Executing POST against " + uri + " with body " + body + "...");
 WebTarget webTarget = client.target(uri);
 Invocation.Builder invocationBuilder =  webTarget.request(MediaType.APPLICATION_JSON);
 Response response = invocationBuilder.post(Entity.json(body));
 int statusCode = response.getStatus();
 if (statusCode != Response.Status.OK.getStatusCode()) {
  throw new HTTPException(statusCode);
 }
}

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

private WebTarget noTimeoutResource() {
 final WebTarget target = noTimeoutClient.target(uri);
 if (!isNullOrEmpty(apiVersion)) {
  return target.path(apiVersion);
 }
 return target;
}

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

Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");

Client client = ClientBuilder.newClient();

WebTarget resource = client.target("http://localhost:8080/someresource");

Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);

Response response = request.get();

if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
  System.out.println("Success! " + response.getStatus());
  System.out.println(response.getEntity());
} else {
  System.out.println("ERROR! " + response.getStatus());    
  System.out.println(response.getEntity());
}

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

@Benchmark
public Response post() throws Exception {
  return client.target("foo").request().post(Entity.text("bar"));
}

代码示例来源:origin: signalapp/Signal-Server

public DirectoryReconciliationResponse sendChunk(DirectoryReconciliationRequest request) {
 return client.target(replicationUrl)
        .path("/v1/directory/reconcile")
        .request(MediaType.APPLICATION_JSON_TYPE)
        .put(Entity.json(request), DirectoryReconciliationResponse.class);
}

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

public static void main(String[] args) {
  Client client = ClientBuilder.newClient();

  client.property(ClientProperties.CONNECT_TIMEOUT, 1000);
  client.property(ClientProperties.READ_TIMEOUT,    1000);

  WebTarget target = client.target("http://1.2.3.4:8080");

  try {
    String responseMsg = target.path("application.wadl").request().get(String.class);
    System.out.println("responseMsg: " + responseMsg);
  } catch (ProcessingException pe) {
    pe.printStackTrace();
  }
}

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

@Override
public TokenResult refreshAccessToken(final String refreshToken) {
  refreshTokenProperties.put(OAuth2Parameters.REFRESH_TOKEN, refreshToken);
  final Form form = new Form();
  for (final Map.Entry<String, String> entry : refreshTokenProperties.entrySet()) {
    form.param(entry.getKey(), entry.getValue());
  }
  final Response response = client.target(refreshTokenUri)
      .request(MediaType.APPLICATION_JSON_TYPE)
      .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
  if (response.getStatus() != 200) {
    throw new ProcessingException(LocalizationMessages.ERROR_FLOW_REQUEST_REFRESH_TOKEN(response.getStatus()));
  }
  this.tokenResult = response.readEntity(TokenResult.class);
  return tokenResult;
}

代码示例来源:origin: aol/micro-server

public T get(final String url) {
  
  
  final WebTarget webResource = client.target(url);
  
  String s = webResource.request(accept).accept(accept)
      .get(String.class);
  
                  
  return  buildResponse(s);
  
      
  
}
private T buildResponse(

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

public static void main(String[] args) {
  try {
    System.out.println("\"Hello World\" Jersey OpenTracing Example App");
    prepare();
    final ResourceConfig resourceConfig = new ResourceConfig(TracedResource.class,
        OpenTracingFeature.class,
        ReqFilterA.class, ReqFilterB.class,
        RespFilterA.class, RespFilterB.class);
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig, false);
    Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow));
    server.start();
    System.out.println(String.format("Application started.\nTry out %s/application.wadl\n"
        + "Stop the application using CTRL+C", BASE_URI));
    // do the first "example" request with tracing-enabled client to show something in Jaegger UI,
    // include some weird headers and accepted types, that will be visible in the span's tags
    Client client = ClientBuilder.newBuilder().register(OpenTracingFeature.class).build();
    client.target(BASE_URI).path("resource/managedClient").request()
        .accept("text/plain", "application/json", "*/*")
        .header("foo", "bar")
        .header("foo", "baz")
        .header("Hello", "World").get();
    Thread.currentThread().join();
  } catch (IOException | InterruptedException ex) {
    Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
  }
}

代码示例来源:origin: apache/storm

private void init() {
  final ApacheConnectorProvider apacheConnectorProvider = new ApacheConnectorProvider();
  final ClientConfig clientConfig = new ClientConfig().connectorProvider(apacheConnectorProvider);
  // transfer encoding should be set as jersey sets it on by default.
  clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING,
      enableChunkedEncoding ? RequestEntityProcessing.CHUNKED : RequestEntityProcessing.BUFFERED);
  client = ClientBuilder.newClient(clientConfig);
  target = client.target(urlString).path(PUT_PATH);
  if(sync) {
    // need to add an empty string else it is nto added as query param.
    target = target.queryParam("sync", "").queryParam("sync_timeout", syncTimeout);
  }
  if(responseType != ResponseType.None) {
    // need to add an empty string else it is nto added as query param.
    target = target.queryParam(responseType.value, "");
  }
  LOG.info("target uri [{}]", target.getUri());
}

相关文章