當前位置: 首頁>>代碼示例>>Java>>正文


Java Client.close方法代碼示例

本文整理匯總了Java中javax.ws.rs.client.Client.close方法的典型用法代碼示例。如果您正苦於以下問題:Java Client.close方法的具體用法?Java Client.close怎麽用?Java Client.close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.ws.rs.client.Client的用法示例。


在下文中一共展示了Client.close方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: registerUser

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
private static void registerUser(String url, MediaType mediaType) {
    System.out.println("Registering user via " + url);
    User user = new User(1L, "larrypage");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().post(Entity.entity(user, mediaType));

    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
開發者ID:flychao88,項目名稱:dubbocloud,代碼行數:18,代碼來源:RestClient.java

示例2: callTokenService

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
/**
 * Invoke the token web service with specified parameters.
 */
@Nullable
private AccessTokenResponse callTokenService( @Nonnull final MultivaluedMap<String, String> parameters )
{
  final ClientBuilder builder =
    ClientBuilder.newBuilder().register( JacksonFeature.class );
  final String clientSecret = _config.getClientSecret();
  if ( null != clientSecret )
  {
    builder.register( new BasicAuthFilter( _config.getClientID(), clientSecret ) );
  }
  final Client client = builder.build();
  try
  {
    final WebTarget target = client.
      target( _config.getServerUrl() ).
      path( "/realms/" ).path( _config.getRealm() ).path( "/protocol/openid-connect/token" );
    final Response response = target.
      request( MediaType.APPLICATION_FORM_URLENCODED ).
      accept( MediaType.APPLICATION_JSON ).
      post( Entity.form( parameters ) );
    if ( Response.Status.Family.SUCCESSFUL == response.getStatusInfo().getFamily() )
    {
      return response.readEntity( AccessTokenResponse.class );
    }
    else
    {
      return null;
    }
  }
  finally
  {
    client.close();
  }
}
 
開發者ID:realityforge,項目名稱:keycloak-jaxrs-client-authfilter,代碼行數:38,代碼來源:Keycloak.java

示例3: closeQuietly

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
public static void closeQuietly(Client client) {
    if (client != null) {
        try {
            client.close();
        } catch (Exception e) {
            LOG.debug("Ignoring exception closing client: " + e, e);
        }
    }
}
 
開發者ID:fabric8-launcher,項目名稱:launcher-backend,代碼行數:10,代碼來源:CreateBuildConfigStep.java

示例4: testJaxRSOptionsDeleteTypes

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
@Test
@RunAsClient
public void testJaxRSOptionsDeleteTypes() throws Exception {
	logger.info("start JaxRS options delete test");
	Client client = newClient();
	WebTarget target = client.target(url + "services/receiver/options");
	Response response = target.request().options();
	String calledMethod = response.getHeaderString("calledMethod");
	double value = response.readEntity(Double.class);
	assertEquals("options implemented: ", 88.99, value, 0.0);
	client.close();
	assertEquals("The filter registerCall is called only for @Logged services", OPTIONS, calledMethod);
	client = newClient();
	target = client.target(url + "services/receiver/delete");
	response = target.request().delete();
	calledMethod = response.getHeaderString("calledMethod");
	value = response.readEntity(Double.class);
	assertEquals("delete implemented: ", 99.66, value, 0.0);
	client.close();
	assertEquals("The filter registerCall is called only for @Logged services", DELETE, calledMethod);
	client = newClient();
	target = client.target(url + "services/receiver/header");
	Builder builder = target.request().header("my_new_header", "Hi all");
	response = builder.get();
	calledMethod = response.getHeaderString("calledMethod");
	String valueStr = response.readEntity(String.class);
	assertEquals("head implemented: ", "Hi all", valueStr);
	client.close();
	assertNotEquals("The filter registerCall is called only for @Logged services", HEAD, calledMethod);
	client = newClient();
	target = client.target(url + "services/receiver/headerWithContext");
	builder = target.request(TEXT_PLAIN).header("my_new_header", "Hi allll");
	response = builder.get();
	calledMethod = response.getHeaderString("calledMethod");
	valueStr = response.readEntity(String.class);
	assertEquals("head implemented: ", "Hi allll", valueStr);
	client.close();
	assertNotEquals("The filter registerCall is called only for @Logged services", HEAD, calledMethod);
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Java-EE-Development-with-WildFly,代碼行數:40,代碼來源:OtherTestCase.java

示例5: testJaxRSPut

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
@Test
public void testJaxRSPut() throws Exception {
	logger.info("start JaxRS other request types test");
	Client client = newClient();
	WebTarget target = client.target(url + "services/calculator/div");
	Entity<List<Double>> valuesAsList = entity(asList(new Double[] { 4.5, 6.7 }), APPLICATION_JSON);
	Response response = target.request(APPLICATION_JSON_TYPE).put(valuesAsList);
	double value = response.readEntity(Double.class);
	response.close();
	client.close();
	assertEquals("sum implemented: ", 0.6716417910447761, value, 0.0);
	assertEquals("The filter registerOperation is called", PUT, calledMethod);
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Java-EE-Development-with-WildFly,代碼行數:14,代碼來源:RestTestCase.java

示例6: obtainAccessToken

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
public String obtainAccessToken(String username, String password) {
    Form form = new Form();
    form.param("grant_type", "password");
    form.param("username", username);
    form.param("password", password);
    form.param("client_id", deployment.getClientId());
    String secret = deployment.getClientCredentials().get("secret").toString();
    form.param("client_secret", secret);
    Client client = null;
    try {
        ClientBuilder clientBuilder = ClientBuilder.newBuilder();
        SSLContext sslcontext = deployment.getSSLContext();
        if(sslcontext != null) {
            client = clientBuilder.sslContext(sslcontext).hostnameVerifier(new AnyHostnameVerifier()).build();
        } else {
            client = clientBuilder.build();
        }

        String tokenURL = String.format("%s/auth/realms/%s/protocol/openid-connect/token",
                deployment.getAuthServerUrl(), deployment.getRealm());
        WebTarget target = client.target(tokenURL);
        if(deployment.getDebug() > 0)
            target.register(new LoggingFilter());
        String json = target.request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
        AccessToken accessToken = JsonSerialization.readValue(json, AccessToken.class);
        return accessToken.getToken();
    } catch (Exception e) {
        throw new RuntimeException("Failed to request token", e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}
 
開發者ID:obsidian-toaster-quickstarts,項目名稱:redhat-sso,代碼行數:36,代碼來源:AuthzClient.java

示例7: getGreeting

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
private static Greeting getGreeting(String url, String token, String from) {
    Client client = ClientBuilder.newClient();
    try {
        WebTarget target = client.target(url);
        System.out.println("URL : " + url);
        target.register((ClientRequestFilter) requestContext -> {
            requestContext.getHeaders().add("Authorization", "Bearer " + token);
        });
        IGreeting greetingClient = ((ResteasyWebTarget) target).proxy(IGreeting.class);
        return greetingClient.greeting(from);
    } finally {
        client.close();
    }
}
 
開發者ID:obsidian-toaster-quickstarts,項目名稱:redhat-sso,代碼行數:15,代碼來源:SsoIT.java

示例8: getUser

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
private static void getUser(String url) {
    System.out.println("Getting user via " + url);
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().get();
    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
開發者ID:flychao88,項目名稱:dubbocloud,代碼行數:16,代碼來源:RestClient.java

示例9: uploadZip

import javax.ws.rs.client.Client; //導入方法依賴的package包/類
@POST
@javax.ws.rs.Path("/commands/{commandName}/missioncontrol")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadZip(JsonObject content,
                          @PathParam("commandName") @DefaultValue(DEFAULT_COMMAND_NAME) String commandName,
                          @Context HttpHeaders headers)
        throws Exception {
    validateCommand(commandName);
    Path path = Files.createTempDirectory("projectDir");
    try (CommandController controller = getCommand(commandName, path, headers)) {
        helper.populateControllerAllInputs(content, controller);
        if (controller.isValid()) {
            Result result = controller.execute();
            if (result instanceof Failed) {
                return Response.serverError().entity(result.getMessage()).build();
            } else {
                Map<String, String> returnMap = Results.getEntityAsMap(result);
                UISelection<?> selection = controller.getContext().getSelection();
                Path projectPath = Paths.get(selection.get().toString());
                String artifactId = returnMap.getOrDefault("named", "booster");
                byte[] zipContents = io.fabric8.launcher.web.forge.util.Paths.zip(artifactId, projectPath);
                Client client = ClientBuilder.newBuilder().build();
                try {
                    WebTarget target = client.target(missionControlURI)
                            .property(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA);

                    // Create request body
                    MultipartFormDataOutput form = new MultipartFormDataOutput();
                    form.addFormData("file", new ByteArrayInputStream(zipContents),
                                     MediaType.MULTIPART_FORM_DATA_TYPE, "project.zip");

                    returnMap.forEach((k, v) -> {
                        if (v == null) {
                            log.warning("No data found for key " + k);
                        } else {
                            form.addFormData(k, v, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
                        }
                    });

                    // Execute POST Request
                    Response response = target.request()
                            .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA)
                            // Propagate Authorization header
                            .header(HttpHeaders.AUTHORIZATION, headers.getHeaderString(HttpHeaders.AUTHORIZATION))
                            .post(Entity.entity(form, MediaType.MULTIPART_FORM_DATA_TYPE));
                    if (response.getStatus() == Status.OK.getStatusCode()) {
                        return Response.ok(response.readEntity(String.class), MediaType.APPLICATION_JSON).build();
                    } else {
                        return Response.status(response.getStatusInfo()).build();
                    }
                } finally {
                    client.close();
                }
            }
        } else {
            JsonObjectBuilder builder = createObjectBuilder();
            helper.describeValidation(builder, controller);
            return Response.status(Status.PRECONDITION_FAILED).entity(builder.build()).build();
        }
    } finally {
        directoriesToDelete.offer(path);
    }
}
 
開發者ID:fabric8-launcher,項目名稱:launcher-backend,代碼行數:65,代碼來源:LaunchResource.java


注:本文中的javax.ws.rs.client.Client.close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。