本文整理了Java中javax.ws.rs.client.Client
类的一些代码示例,展示了Client
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Client
类的具体详情如下:
包路径:javax.ws.rs.client.Client
类名称:Client
[英]Client is the main entry point to the fluent API used to build and execute client requests in order to consume responses returned.
Clients are heavy-weight objects that manage the client-side communication infrastructure. Initialization as well as disposal of a Client instance may be a rather expensive operation. It is therefore advised to construct only a small number of Client instances in the application. Client instances must be #close() before being disposed to avoid leaking resources.
[中]客户机是fluent API的主要入口点,该API用于构建和执行客户机请求,以使用返回的响应。
客户端是管理客户端通信基础结构的重要对象。初始化和处理客户机实例可能是一项相当昂贵的操作。因此,建议在应用程序中只构造少量客户端实例。客户端实例在被释放之前必须是#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: dropwizard/dropwizard
@Override
public void stop() throws Exception {
client.close();
}
});
代码示例来源:origin: jersey/jersey
@Override
public void run() {
final Client resourceClient = ClientBuilder.newClient();
resourceClient.register(new MoxyJsonFeature());
final WebTarget messageStreamResource = resourceClient.target(App.getApiUri()).path("message/stream");
Message message = null;
try {
while (!cancelled && (message = messages.take()) != null) {
msgListener.onMessage(message);
final Response r = messageStreamResource.request().put(Entity.json(message));
if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
LOGGER.warning("Unexpected PUT message response status code: " + r.getStatus());
}
}
if (message == null) {
LOGGER.info("Timed out while waiting for a message.");
}
} catch (InterruptedException ex) {
LOGGER.log(Level.WARNING, "Waiting for a message has been interrupted.", ex);
} finally {
readerHandle.cancel(true);
msgListener.onComplete();
}
}
});
代码示例来源: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
private Client configureClient(Client client) {
if (client == null) {
client = ClientBuilder.newClient();
}
final Configuration config = client.getConfiguration();
if (!config.isRegistered(AuthCodeGrantImpl.DefaultTokenMessageBodyReader.class)) {
client.register(AuthCodeGrantImpl.DefaultTokenMessageBodyReader.class);
}
if (!config.isRegistered(JacksonFeature.class)) {
client.register(JacksonFeature.class);
}
return client;
}
代码示例来源: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: aol/micro-server
public Response postString(String url, String payload) {
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(url);
Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);
return request.post(Entity.entity(payload,MediaType.APPLICATION_JSON));
}
代码示例来源: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: jersey/jersey
.keyPassword("asdfgh");
final Client client = ClientBuilder.newBuilder().sslContext(sslConfig.createSSLContext()).build();
client.property(ClientProperties.CONNECT_TIMEOUT, 2000)
.register(new MoxyJsonFeature())
.register(HttpAuthenticationFeature.basic(App.getTwitterUserName(), App.getTwitterUserPassword()))
.register(GZipEncoder.class);
final Response response = client.target("https://stream.twitter.com/1.1/statuses/filter.json")
.queryParam("track", keywords)
.request(MediaType.APPLICATION_JSON_TYPE)
.header(HttpHeaders.HOST, "stream.twitter.com")
.header(HttpHeaders.USER_AGENT, "Jersey/2.0")
.header(HttpHeaders.ACCEPT_ENCODING, "gzip")
.get();
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
LOGGER.log(Level.WARNING, "Error connecting to Twitter Streaming API: " + response.getStatus());
msgListener.onError();
return;
final ChunkedInput<Message> chunks = response.readEntity(new GenericType<ChunkedInput<Message>>() {
});
try {
代码示例来源:origin: aol/micro-server
public String get(String url) {
Client client = ClientBuilder.newClient();
WebTarget resource = client.target(url);
Builder request = resource.request();
request.accept(MediaType.TEXT_PLAIN);
return request.get(String.class);
}
代码示例来源: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
System.out.println(String.format("\nStarting to execute %d requests:\n", config.requests));
final Client client = ClientBuilder.newClient();
final WebTarget echoResource = client.target(config.baseUri).path("long-running/{mode}/{echo}")
.resolveTemplate("mode", (config.sync) ? "sync" : "async");
for (int i = 0; i < config.requests; i++) {
final int reqId = i;
echoResource.resolveTemplate("echo", reqId).request().async().get(new InvocationCallback<String>() {
private final AtomicInteger retries = new AtomicInteger(0);
client.close();
代码示例来源:origin: apache/cxf
@Test
public void testGetBookSpecTemplate() {
String address = "http://localhost:" + PORT + "/bookstore/{a}";
Client client = ClientBuilder.newClient();
client.register((Object)ClientFilterClientAndConfigCheck.class);
client.register(new BTypeParamConverterProvider());
client.property("clientproperty", "somevalue");
WebTarget webTarget = client.target(address).path("{b}")
.resolveTemplate("a", "bookheaders").resolveTemplate("b", "simple");
Invocation.Builder builder = webTarget.request("application/xml").header("a", new BType());
Response r = builder.get();
Book book = r.readEntity(Book.class);
assertEquals(124L, book.getId());
assertEquals("b", r.getHeaderString("a"));
}
@Test
代码示例来源:origin: apache/cxf
@Test
public void testGetSetEntityStreamLambda() {
String address = "http://localhost:" + PORT + "/bookstore/entityecho";
String entity = "BOOKSTORE";
Client client = ClientBuilder.newClient();
client.register((ClientRequestFilter) context -> {
context.setEntityStream(new ReplacingOutputStream(context.getEntityStream(), 'X', 'O'));
});
WebTarget target = client.target(address);
Response response = target.request().post(
Entity.entity(entity.replace('O', 'X'), "text/plain"));
assertEquals(entity, response.readEntity(String.class));
}
代码示例来源:origin: aol/micro-server
@Test
public void runAppAndBasicTest() throws InterruptedException, ExecutionException{
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("http://localhost:8080/simple-app/single/ping");
Builder request = resource.request();
request.accept(MediaType.TEXT_PLAIN);
assertTrue(request.get().getHeaders().containsKey("Access-Control-Allow-Origin"));
}
代码示例来源:origin: apache/cxf
@Test
public void testGetBookSpec() {
String address = "http://localhost:" + PORT + "/bookstore/bookheaders/simple";
Client client = ClientBuilder.newClient();
client.register((Object)ClientFilterClientAndConfigCheck.class);
client.register(new BTypeParamConverterProvider());
client.property("clientproperty", "somevalue");
WebTarget webTarget = client.target(address);
Invocation.Builder builder = webTarget.request("application/xml").header("a", new BType());
Response r = builder.get();
Book book = r.readEntity(Book.class);
assertEquals(124L, book.getId());
assertEquals("b", r.getHeaderString("a"));
}
代码示例来源:origin: Texera/texera
@Test
@Ignore
public void getDictionaryPath() throws Exception {
Client client = new JerseyClientBuilder(RULE.getEnvironment()).build("test client");
client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
client.property(ClientProperties.READ_TIMEOUT, 5000);
client.register(MultiPartFeature.class);
Response response = client.target(
String.format("http://localhost:%d/api/resources/dictionary/?name=dictname", RULE.getLocalPort()))
.request()
.get();
assertThat(response.getStatus()).isEqualTo(200);
}
}
代码示例来源:origin: org.pacesys.openstack4j.connectors/openstack4j-jersey2
private void initialize() {
Client client = ClientFactory.create(request.getConfig());
//try to set unsupported HTTP method. In our case used for PATCH.
if( request.getMethod().name()=="PATCH" )
client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
WebTarget target = client.target(request.getEndpoint()).path(request.getPath());
if (HttpLoggingFilter.isLoggingEnabled())
target.register(new LoggingFilter(Logger.getLogger("os"), 10000));
target = populateQueryParams(target, request);
invocation = target.request(MediaType.APPLICATION_JSON);
populateHeaders(invocation, request);
entity = (request.getEntity() == null) ? null : Entity.entity(request.getEntity(), request.getContentType());
}
代码示例来源: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());
}
代码示例来源:origin: jersey/jersey
@Benchmark
public Response post() throws Exception {
return client.target("foo").request().post(Entity.text("bar"));
}
内容来源于网络,如有侵权,请联系作者删除!