本文整理汇总了Java中io.undertow.client.ClientRequest类的典型用法代码示例。如果您正苦于以下问题:Java ClientRequest类的具体用法?Java ClientRequest怎么用?Java ClientRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ClientRequest类属于io.undertow.client包,在下文中一共展示了ClientRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testHttp2Post
import io.undertow.client.ClientRequest; //导入依赖的package包/类
/**
* This is an example for post request. Please note that you need to set header TRANSFER_ENCODING
* and pass the request body into the callback function.
*
* @throws Exception
*/
public void testHttp2Post() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final ClientConnection connection = client.connect(new URI("https://localhost:8443"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
try {
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
if(securityEnabled) {
// call OAuth 2.0 provider service to get a JWT access token here and
// put it into the request header. Optionally, you can put a traceabilityId
// into the header.
}
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
connection.sendRequest(request, client.createClientCallback(reference, latch, "post"));
latch.await(100, TimeUnit.MILLISECONDS);
} finally {
IoUtils.safeClose(connection);
}
System.out.println("testHttp2Post: statusCode = " + reference.get().getResponseCode() + " body = " + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
}
示例2: sendAuthenticationRequest
import io.undertow.client.ClientRequest; //导入依赖的package包/类
/**
* Executed when a pooled connection is acquired.
*/
private void sendAuthenticationRequest(HttpServerExchange serverExchange, PooledConnection connection) {
AuthContext context = serverExchange.getAttachment(AUTH_CONTEXT_KEY);
String verb = getVerb(serverExchange);
String resource;
// if we are not dealing with a query
if (!isQuery(serverExchange)) {
// is USER_WRITE_ACCESS is disabled, then use the legacy check.
// Otherwise check using the actual resource (eg 'hawkular-metrics', 'hawkular-alerts', etc)
if (USER_WRITE_ACCESS.equalsIgnoreCase("true")) {
resource = RESOURCE;
} else {
resource= resourceName;
}
} else {
resource = RESOURCE;
}
context.subjectAccessReview = generateSubjectAccessReview(context.tenant, verb, resource);
ClientRequest request = buildClientRequest(context);
context.clientRequestStarting();
connection.sendRequest(request, new RequestReadyCallback(serverExchange, connection));
}
示例3: testMultipleHttp2Get
import io.undertow.client.ClientRequest; //导入依赖的package包/类
public void testMultipleHttp2Get(int round) throws Exception {
final Http2Client client = Http2Client.getInstance();
final List<AtomicReference<ClientResponse>> references = new CopyOnWriteArrayList<>();
final CountDownLatch latch = new CountDownLatch(round);
final ClientConnection connection = client.connect(new URI("https://localhost:8443"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
try {
connection.getIoThread().execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < round; i++) {
AtomicReference<ClientResponse> reference = new AtomicReference<>();
references.add(i, reference);
final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath("/get");
request.getRequestHeaders().put(Headers.HOST, "localhost");
connection.sendRequest(request, client.createClientCallback(reference, latch));
}
}
});
latch.await(10, TimeUnit.SECONDS);
/*
for (final AtomicReference<ClientResponse> reference : references) {
System.out.println(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
System.out.println(reference.get().getProtocol().toString());
}
*/
} finally {
IoUtils.safeClose(connection);
}
}
示例4: testMultipleHttp2Post
import io.undertow.client.ClientRequest; //导入依赖的package包/类
public void testMultipleHttp2Post(int round) throws Exception {
final Http2Client client = Http2Client.getInstance();
final List<AtomicReference<ClientResponse>> references = new CopyOnWriteArrayList<>();
final CountDownLatch latch = new CountDownLatch(round);
final ClientConnection connection = client.connect(new URI("https://localhost:8443"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
try {
connection.getIoThread().execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < round; i++) {
AtomicReference<ClientResponse> reference = new AtomicReference<>();
references.add(i, reference);
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
request.getRequestHeaders().put(Headers.HOST, "localhost");
connection.sendRequest(request, client.createClientCallback(reference, latch, "post"));
}
}
});
latch.await(10, TimeUnit.SECONDS);
/*
for (final AtomicReference<ClientResponse> reference : references) {
System.out.println(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
System.out.println(reference.get().getProtocol().toString());
}
*/
} finally {
IoUtils.safeClose(connection);
}
}
示例5: sendRequest
import io.undertow.client.ClientRequest; //导入依赖的package包/类
@Override
public void sendRequest(final ClientRequest request, final ClientCallback<ClientExchange> clientCallback) {
if (anyAreSet(state, UPGRADE_REQUESTED | UPGRADED | CLOSE_REQ | CLOSED)) {
clientCallback.failed(UndertowClientMessages.MESSAGES.invalidConnectionState());
return;
}
final AjpClientExchange AjpClientExchange = new AjpClientExchange(clientCallback, request, this);
if (currentRequest == null) {
initiateRequest(AjpClientExchange);
} else {
pendingQueue.add(AjpClientExchange);
}
}
示例6: AjpClientExchange
import io.undertow.client.ClientRequest; //导入依赖的package包/类
public AjpClientExchange(ClientCallback<ClientExchange> readyCallback, ClientRequest request, AjpClientConnection clientConnection) {
this.readyCallback = readyCallback;
this.request = request;
this.clientConnection = clientConnection;
boolean reqContinue = false;
if (request.getRequestHeaders().contains(Headers.EXPECT)) {
for (String header : request.getRequestHeaders().get(Headers.EXPECT)) {
if (header.equals("100-continue")) {
reqContinue = true;
}
}
}
this.requiresContinue = reqContinue;
}
示例7: sendRequest
import io.undertow.client.ClientRequest; //导入依赖的package包/类
@Override
public void sendRequest(final ClientRequest request, final ClientCallback<ClientExchange> clientCallback) {
count++;
if (anyAreSet(state, UPGRADE_REQUESTED | UPGRADED | CLOSE_REQ | CLOSED)) {
clientCallback.failed(UndertowClientMessages.MESSAGES.invalidConnectionState());
return;
}
final HttpClientExchange httpClientExchange = new HttpClientExchange(clientCallback, request, this);
if (currentRequest == null) {
initiateRequest(httpClientExchange);
} else {
pendingQueue.add(httpClientExchange);
}
}
示例8: HttpClientExchange
import io.undertow.client.ClientRequest; //导入依赖的package包/类
public HttpClientExchange(ClientCallback<ClientExchange> readyCallback, ClientRequest request, HttpClientConnection clientConnection) {
this.readyCallback = readyCallback;
this.request = request;
this.clientConnection = clientConnection;
boolean reqContinue = false;
if (request.getRequestHeaders().contains(Headers.EXPECT)) {
for (String header : request.getRequestHeaders().get(Headers.EXPECT)) {
if (header.equals("100-continue")) {
reqContinue = true;
}
}
}
this.requiresContinue = reqContinue;
}
示例9: executeReceiveRequest
import io.undertow.client.ClientRequest; //导入依赖的package包/类
private void executeReceiveRequest(final TransportRequest transportRequest,
final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
final SettableListenableFuture<WebSocketSession> connectFuture) {
if (logger.isTraceEnabled()) {
logger.trace("Starting XHR receive request for " + url);
}
ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
@Override
public void completed(ClientConnection connection) {
ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
request.getRequestHeaders().add(headerName, url.getHost());
addHttpHeaders(request, headers);
HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
connection.sendRequest(request, createReceiveCallback(transportRequest,
url, httpHeaders, session, connectFuture));
}
@Override
public void failed(IOException ex) {
throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
}
};
this.undertowBufferSupport.httpClientConnect(this.httpClient, clientCallback, url, worker, this.optionMap);
}
示例10: addHttpHeaders
import io.undertow.client.ClientRequest; //导入依赖的package包/类
private static void addHttpHeaders(ClientRequest request, HttpHeaders headers) {
HeaderMap headerMap = request.getRequestHeaders();
for (String name : headers.keySet()) {
for (String value : headers.get(name)) {
headerMap.add(HttpString.tryFromString(name), value);
}
}
}
示例11: testHttp2Get
import io.undertow.client.ClientRequest; //导入依赖的package包/类
/**
* This is a simple example that create a new HTTP 2.0 connection for get request
* and close the connection after the call is done. As you can see that it is using
* a hard coded uri which points to an statically deployed service on fixed ip and port
*
* @throws Exception
*/
public void testHttp2Get() throws Exception {
// Create one CountDownLatch that will be reset in the callback function
final CountDownLatch latch = new CountDownLatch(1);
// Create an HTTP 2.0 connection to the server
final ClientConnection connection = client.connect(new URI("https://localhost:8443"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
// Create an AtomicReference object to receive ClientResponse from callback function
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
try {
final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath("/get");
// this is to ask client module to pass through correlationId and traceabilityId as well as
// getting access token from oauth2 server automatically and attatch authorization headers.
if(securityEnabled) {
// call OAuth 2.0 provider service to get a JWT access token here and
// put it into the request header. Optionally, you can put a traceabilityId
// into the header.
TokenResponse tokenResponse = getAccessToken();
// you should check if the token is expired here
expiration = tokenResponse.getExpiresIn();
String token = tokenResponse.getAccessToken();
// traceabilityId should be a uuid or db sequence
client.addAuthTokenTrace(request, token, "traceabilityId");
}
// send request to server with a callback function provided by Http2Client
connection.sendRequest(request, client.createClientCallback(reference, latch));
// wait for 100 millisecond to timeout the request.
latch.await(100, TimeUnit.MILLISECONDS);
} finally {
// here the connection is closed after one request. It should be used for in frequent
// request as creating a new connection is costly with TLS handshake and ALPN.
IoUtils.safeClose(connection);
}
int statusCode = reference.get().getResponseCode();
String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
System.out.println("testHttp2Get: statusCode = " + statusCode + " body = " + body);
}
示例12: testHttp2GetReuse
import io.undertow.client.ClientRequest; //导入依赖的package包/类
/**
* This is a simple example that create a new HTTP 2.0 connection for get request
* and close the connection after the call is done. As you can see that it is using
* a hard coded uri which points to an statically deployed service on fixed ip and port
*
* @throws Exception
*/
public void testHttp2GetReuse() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath("/get");
if(securityEnabled) {
}
// send request to server with a callback function provided by Http2Client
reusedConnection.sendRequest(request, client.createClientCallback(reference, latch));
// wait for 100 millisecond to timeout the request.
latch.await(100, TimeUnit.MILLISECONDS);
System.out.println("testHttp2GetReuse: statusCode = " + reference.get().getResponseCode() + " body = " + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
}
示例13: testHttp2PostResue
import io.undertow.client.ClientRequest; //导入依赖的package包/类
/**
* This is an example for post request. Please note that you need to set header TRANSFER_ENCODING
* and pass the request body into the callback function.
*
* @throws Exception
*/
public void testHttp2PostResue() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
if(securityEnabled) {
}
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
reusedConnection.sendRequest(request, client.createClientCallback(reference, latch, "post"));
latch.await(100, TimeUnit.MILLISECONDS);
System.out.println("testHttp2PostReuse: statusCode = " + reference.get().getResponseCode() + " body = " + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
}
示例14: getAccessToken
import io.undertow.client.ClientRequest; //导入依赖的package包/类
/**
* In this example, I am going to use a customized grant type to get access token. This grant type assumes
* that the client authenticated the user and send the user info to OAuth 2.0 provider to get an access token.
* Note that the client must be a strusted client.
* @return
*/
private TokenResponse getAccessToken() throws Exception {
TokenResponse tokenResponse = null;
Map<String, String> params = new HashMap<>();
params.put("grant_type", "client_authenticated_user");
params.put("userId", "admin");
params.put("userType", "Employee");
params.put("transit", "12345"); // This is the custom claim that need to be shown in JWT token.
String s = Http2Client.getFormDataString(params);
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
final ClientConnection connection;
try {
// all the connection information should be from client.yml
connection = client.connect(new URI("https://localhost:6882"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/oauth2/token");
request.getRequestHeaders().put(Headers.HOST, "localhost");
request.getRequestHeaders().put(Headers.AUTHORIZATION, "Basic " + encodeCredentials("f7d42348-c647-4efb-a52d-4c5787421e72", "f6h1FTI8Q3-7UScPZDzfXA"));
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
connection.sendRequest(request, client.createClientCallback(reference, latch, s));
latch.await(1, TimeUnit.SECONDS);
String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
tokenResponse = Config.getInstance().getMapper().readValue(body, TokenResponse.class);
} catch (Exception e) {
throw new ClientException(e);
}
return tokenResponse;
}
示例15: toHttpRequest
import io.undertow.client.ClientRequest; //导入依赖的package包/类
@Override
public Object toHttpRequest(ClientRequest clientRequest, Message message) {
Object body = message.getBody();
// set the content type in the response.
String contentType = MessageHelper.getContentType(message);
if (contentType != null) {
// set content-type
clientRequest.getRequestHeaders().put(Headers.CONTENT_TYPE, contentType);
LOG.trace("Content-Type: {}", contentType);
}
TypeConverter tc = message.getExchange().getContext().getTypeConverter();
//copy headers from Message to Request
for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// use an iterator as there can be multiple values. (must not use a delimiter)
final Iterator<?> it = ObjectHelper.createIterator(value, null);
while (it.hasNext()) {
String headerValue = tc.convertTo(String.class, it.next());
if (headerValue != null && headerFilterStrategy != null
&& !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
LOG.trace("HTTP-Header: {}={}", key, headerValue);
clientRequest.getRequestHeaders().add(new HttpString(key), headerValue);
}
}
}
return body;
}