本文整理了Java中io.vertx.ext.web.client.HttpResponse
类的一些代码示例,展示了HttpResponse
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpResponse
类的具体详情如下:
包路径:io.vertx.ext.web.client.HttpResponse
类名称:HttpResponse
暂无
代码示例来源:origin: vert-x3/vertx-examples
@Override
public void start() throws Exception {
WebClient client = WebClient.create(vertx);
client.get(8080, "localhost", "/").send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
System.out.println("Got HTTP response with status " + response.statusCode() + " with data " +
response.body().toString("ISO-8859-1"));
} else {
ar.cause().printStackTrace();
}
});
}
}
代码示例来源:origin: vert-x3/vertx-examples
private void invoke(RoutingContext rc) {
client.get("/luke").as(BodyCodec.string()).send(ar -> {
if (ar.failed()) {
rc.response().end("Unable to call the greeting service: " + ar.cause().getMessage());
} else {
if (ar.result().statusCode() != 200) {
rc.response().end("Unable to call the greeting service - received status:" + ar.result().statusMessage());
} else {
rc.response().end("Greeting service invoked: '" + ar.result().body() + "'");
}
}
});
}
}
代码示例来源:origin: io.vertx/vertx-service-discovery
@Test
public void testPublicationAndConsumptionWithConfigurationAsWebClient(TestContext context) {
Async async = context.async();
// Publish the service
Record record = HttpEndpoint.createRecord("hello-service", "localhost", 8080, "/foo");
discovery.publish(record, rec -> {
Record published = rec.result();
HttpEndpoint.getWebClient(discovery,
new JsonObject().put("name", "hello-service"),
new JsonObject().put("keepAlive", false), found -> {
context.assertTrue(found.succeeded());
context.assertTrue(found.result() != null);
WebClient client = found.result();
client.get("/foo").send(ar -> {
if (ar.failed()) {
context.fail(ar.cause());
}
HttpResponse<Buffer> response = ar.result();
context.assertEquals(response.statusCode(), 200);
context.assertEquals(response.getHeader("connection"), "close");
context.assertEquals(response.body().toString(), "hello");
ServiceDiscovery.releaseServiceObject(discovery, client);
discovery.unpublish(published.getRegistration(), v -> async.complete());
});
});
});
}
代码示例来源:origin: vert-x3/vertx-examples
@Override
public void start() throws Exception {
WebClient client = WebClient.create(vertx);
Buffer body = Buffer.buffer("Hello World");
client.put(8080, "localhost", "/").sendBuffer(body, ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
System.out.println("Got HTTP response with status " + response.statusCode());
} else {
ar.cause().printStackTrace();
}
});
}
}
代码示例来源:origin: vert-x3/vertx-config
private void manageAuthResult(Handler<AsyncResult<Auth>> resultHandler, HttpResponse<Buffer> response) {
if (response.statusCode() != 200) {
resultHandler.handle(VaultException.toFailure(response.statusMessage(), response.statusCode(),
response.bodyAsString()));
} else {
JsonObject object = response.bodyAsJsonObject();
Auth auth = object.getJsonObject("auth").mapTo(Auth.class);
resultHandler.handle(Future.succeededFuture(auth));
}
}
代码示例来源:origin: vert-x3/vertx-examples
@Override
public void start() throws Exception {
WebClient client = WebClient.create(vertx);
client.get(8080, "localhost", "/")
.as(BodyCodec.json(User.class))
.send(ar -> {
if (ar.succeeded()) {
HttpResponse<User> response = ar.result();
System.out.println("Got HTTP response body");
User user = response.body();
System.out.println("FirstName " + user.firstName);
System.out.println("LastName " + user.lastName);
System.out.println("Male " + user.male);
} else {
ar.cause().printStackTrace();
}
});
}
}
代码示例来源:origin: vert-x3/vertx-config
/**
* Write a secret to `path`.
*
* @param path the path
* @param resultHandler the callback invoked with the result
*/
public void write(String path, JsonObject secrets, Handler<AsyncResult<Secret>> resultHandler) {
Objects.requireNonNull(resultHandler);
client.post("/v1/" + Objects.requireNonNull(path))
.putHeader(TOKEN_HEADER, Objects.requireNonNull(getToken(), "The token must be set"))
.sendJsonObject(Objects.requireNonNull(secrets, "The secret must be set"),
ar -> {
if (ar.failed()) {
resultHandler.handle(VaultException.toFailure("Unable to access the Vault", ar.cause()));
return;
}
HttpResponse<Buffer> response = ar.result();
if (response.statusCode() == 200 || response.statusCode() == 204) {
resultHandler.handle(Future.succeededFuture(response.bodyAsJson(Secret.class)));
} else {
resultHandler.handle(VaultException.toFailure(response.statusMessage(), response.statusCode(),
response.bodyAsString()));
}
});
}
代码示例来源:origin: vert-x3/vertx-service-discovery
private Future<JsonArray> retrieveServices(String token) {
Future<JsonArray> future = Future.future();
String path = "/api/v1/namespaces/" + namespace + "/services";
client.get(path)
.putHeader("Authorization", "Bearer " + token)
.send(resp -> {
if (resp.failed()) {
future.fail(resp.cause());
} else if (resp.result().statusCode() != 200) {
future.fail("Unable to retrieve services from namespace " + namespace + ", status code: "
+ resp.result().statusCode() + ", content: " + resp.result().bodyAsString());
} else {
HttpResponse<Buffer> response = resp.result();
JsonArray items = response.bodyAsJsonObject().getJsonArray("items");
if (items == null) {
future.fail("Unable to retrieve services from namespace " + namespace + " - no items");
} else {
future.complete(items);
watch(client, token, response.bodyAsJsonObject().getJsonObject("metadata").getString("resourceVersion"));
}
}
});
return future;
}
代码示例来源:origin: io.vertx/vertx-web-client
@Test
public void testSessionHeaders(TestContext context) {
String headerName = "x-client-header";
String headerVal = "MY-HEADER";
prepareServer(context, req -> {
req.response().setChunked(true);
if (headerVal.equals(req.getHeader(headerName))) {
req.response().write("OK");
} else {
req.response().write("ERR");
}
});
Async async = context.async();
client.addHeader(headerName, headerVal);
client.get("/").send(ar -> {
context.assertTrue(ar.succeeded());
HttpResponse<Buffer> res = ar.result();
context.assertEquals(200, res.statusCode());
context.assertEquals("OK", res.bodyAsString());
async.complete();
});
}
代码示例来源:origin: silentbalanceyh/vertx-zero
/**
* Success ( 200 )
*/
private static void syncSuccess(
final HttpServerResponse response,
final HttpResponse<Buffer> clientResponse) {
final Buffer data = clientResponse.bodyAsBuffer();
// Copy header
syncSuccess(response,
clientResponse.headers(),
clientResponse.statusCode(),
clientResponse.statusMessage(),
data);
}
代码示例来源:origin: EnMasseProject/enmasse
protected <T> void responseHandler(AsyncResult<HttpResponse<T>> ar, CompletableFuture<T> promise, int expectedCode,
String warnMessage) {
try {
if (ar.succeeded()) {
HttpResponse<T> response = ar.result();
T body = response.body();
if (response.statusCode() != expectedCode) {
log.error("expected-code: {}, response-code: {}, body: {}", expectedCode, response.statusCode(), response.body());
promise.completeExceptionally(new RuntimeException("Status " + response.statusCode() + " body: " + (body != null ? body.toString() : null)));
} else if (response.statusCode() < HTTP_OK || response.statusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
promise.completeExceptionally(new RuntimeException(body.toString()));
} else {
promise.complete(ar.result().body());
}
} else {
log.warn(warnMessage);
promise.completeExceptionally(ar.cause());
}
} catch (io.vertx.core.json.DecodeException decEx) {
if (ar.result().bodyAsString().toLowerCase().contains("application is not available")) {
log.warn("'{}' is not available.", apiClientName(), ar.cause());
throw new IllegalStateException(String.format("'%s' is not available.", apiClientName()));
} else {
log.warn("Unexpected object received", ar.cause());
throw new IllegalStateException("JsonObject expected, but following object was received: " + ar.result().bodyAsString());
}
}
}
代码示例来源:origin: io.vertx/vertx-consul-client
@Override
public ConsulClient getKeysWithOptions(String keyPrefix, BlockingQueryOptions options, Handler<AsyncResult<List<String>>> resultHandler) {
Query query = Query.of("recurse", true).put("keys", true).put(options);
request(KV_VALID_CODES, HttpMethod.GET, "/v1/kv/" + urlEncode(keyPrefix), query, null, resultHandler, resp -> {
if (resp.statusCode() == HttpResponseStatus.NOT_FOUND.code()) {
return new ArrayList<>();
} else {
return resp.bodyAsJsonArray().stream().map(Object::toString).collect(Collectors.toList());
}
});
return this;
}
代码示例来源:origin: vert-x3/vertx-config
/**
* Deletes a secret from `path`.
*
* @param path the path
* @param resultHandler the callback invoked with the result
*/
public void delete(String path, Handler<AsyncResult<Void>> resultHandler) {
Objects.requireNonNull(resultHandler);
client.delete("/v1/" + Objects.requireNonNull(path))
.putHeader(TOKEN_HEADER, Objects.requireNonNull(getToken(), "The token must be set"))
.send(ar -> {
if (ar.failed()) {
resultHandler.handle(VaultException.toFailure("Unable to access the Vault", ar.cause()));
return;
}
HttpResponse<Buffer> response = ar.result();
if (response.statusCode() != 204) {
resultHandler.handle(VaultException.toFailure(response.statusMessage(), response.statusCode(),
response.bodyAsString()));
} else {
resultHandler.handle(Future.succeededFuture());
}
});
}
代码示例来源:origin: io.vertx/vertx-web-client
@Test
public void testResponseUnknownContentTypeBodyAsJsonObject() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.bodyAsJsonObject());
testComplete();
}));
await();
}
代码示例来源:origin: io.vertx/vertx-rx-java
/**
* @return the response body decoded as , or <code>null</code> if a codec other than was used
*/
public JsonObject bodyAsJsonObject() {
if (cached_9 != null) {
return cached_9;
}
JsonObject ret = delegate.bodyAsJsonObject();
cached_9 = ret;
return ret;
}
代码示例来源:origin: io.vertx/vertx-consul-client
@Override
public ConsulClient getValuesWithOptions(String keyPrefix, BlockingQueryOptions options, Handler<AsyncResult<KeyValueList>> resultHandler) {
Query query = Query.of("recurse", true).put(options);
request(KV_VALID_CODES, HttpMethod.GET, "/v1/kv/" + urlEncode(keyPrefix), query, null, resultHandler, resp -> {
if (resp.statusCode() == HttpResponseStatus.NOT_FOUND.code()) {
return new KeyValueList();
} else {
List<KeyValue> list = resp.bodyAsJsonArray().stream().map(obj -> KVParser.parse((JsonObject) obj)).collect(Collectors.toList());
return new KeyValueList().setList(list).setIndex(Long.parseLong(resp.headers().get(INDEX_HEADER)));
}
});
return this;
}
代码示例来源:origin: io.vertx/vertx-consul-client
if (h.succeeded()) {
HttpResponse<Buffer> resp = h.result();
if (validCodes.contains(resp.statusCode())) {
T mapped;
try {
resultHandler.handle(Future.failedFuture(resp.statusMessage()));
代码示例来源:origin: io.vertx/vertx-web-client
@Test
public void testResponseUnknownContentTypeBodyAsJsonMapped() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.bodyAsJson(WineAndCheese.class));
testComplete();
}));
await();
}
代码示例来源:origin: EliMirren/VX-API-Gateway
if (tranHeaders != null && tranHeaders.size() > 0) {
tranHeaders.forEach(h -> {
rct.response().putHeader(h, result.getHeader(h) == null ? "" : result.getHeader(h));
});
String token = res.result().getHeader(getTokenName);
if (token != null && !"".equals(token)) {
rct.session().put(saveTokenName, token);
.putHeader(HttpHeaderConstant.CONTENT_TYPE, api.getContentType()).setChunked(true).write(result.body());
if (isNext) {
rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>succeededFuture(true));// 告诉后置处理器当前操作成功执行
response.end();
trackInfo.setResponseBufferLen(result.body() == null ? 0 : result.body().length());
trackInfo.setEndTime(Instant.now());
} else {
代码示例来源:origin: io.vertx/vertx-rx-java
/**
* @return the response body decoded as a <code>String</code>, or <code>null</code> if a codec other than was used
*/
public String bodyAsString() {
if (cached_8 != null) {
return cached_8;
}
String ret = delegate.bodyAsString();
cached_8 = ret;
return ret;
}
内容来源于网络,如有侵权,请联系作者删除!