Java Code Examples for io.vertx.core.http.HttpClientRequest#putHeader()

The following examples show how to use io.vertx.core.http.HttpClientRequest#putHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataArraySsv(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/ssv");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1 2 3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 2
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataArrayPipes(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/pipes");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1|2|3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 3
Source File: NetworkUtils.java    From AlipayWechatPlatform with GNU General Public License v3.0 6 votes vote down vote up
public static void asyncPostStringWithData(String url, String body, ContentType type, String encode, Handler<String> callback) {
        checkInitialized();
        HttpClientRequest req = client.requestAbs(HttpMethod.POST, url, resp -> {
            resp.bodyHandler(buf -> {
                callback.handle(buf.toString());
            });
        });
        switch (type) {
            case XML:
                req.putHeader("content-type", "application/xml;charset=" + encode);
                break;
            case JSON:
                req.putHeader("content-type", "application/json;charset=" + encode);
                break;
            case FORM:
                req.putHeader("content-type", "application/x-www-form-urlencoded" + encode);
                break;
        }
//        req.putHeader("content-length", String.valueOf(body.length()));
//        req.write(body);
        req.end(body, encode);
    }
 
Example 4
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataArray(TestContext context) throws UnsupportedEncodingException {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1,2,3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 5
Source File: TranslatorExampleTest.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
@Test(timeout = DEFAULT_TIMEOUT)
public void testTranslator(TestContext context) throws InterruptedException {
    Async async = context.async();
    HttpClient client = vertx.createHttpClient();
    HttpClientRequest request = client.request(HttpMethod.POST, 8080, "localhost", "/translate");
    request.putHeader("Content-type", "application/x-www-form-urlencoded");
    request.handler((response) -> {
        if (response.statusCode() == 200) {
            response.bodyHandler((buffer) -> {
                context.assertEquals("[{\"word\":\"Hello\",\"translations\":[\"ahoj\",\"dobry den\"]},{\"word\":\"world\",\"translations\":[\"svet\"]}]",
                        buffer.toString());
                client.close();
                async.complete();
            });
        }
    });
    request.end("sentence=Hello world");
}
 
Example 6
Source File: OkapiPerformance.java    From okapi with Apache License 2.0 6 votes vote down vote up
public void doLogin(TestContext context) {
  String doc = "{" + LS
          + "  \"tenant\" : \"t1\"," + LS
          + "  \"username\" : \"peter\"," + LS
          + "  \"password\" : \"peter-password\"" + LS
          + "}";
  HttpClientRequest req = HttpClientLegacy.post(httpClient, port, "localhost", "/authn/login", response -> {
    context.assertEquals(200, response.statusCode());
    String headers = response.headers().entries().toString();
    okapiToken = response.getHeader("X-Okapi-Token");
    response.endHandler(x -> {
      useItWithGet(context);
    });
  });
  req.putHeader("X-Okapi-Tenant", okapiTenant);
  req.end(doc);
}
 
Example 7
Source File: ApiKeyAuthTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testApiKeyAuthDummyKoBadCredentials(TestContext context) {
    Async async = context.async();
    
    HttpClientRequest req = httpClient.get(TEST_PORT, TEST_HOST, "/dummy", response -> {
    	context.assertEquals(response.statusCode(), 401);
        async.complete();
    });
    req.putHeader("apikey-dummy", ALL_API_KEY_AUTH);
    req.end();
}
 
Example 8
Source File: ProxyTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
private void myEdgeCallTest(RoutingContext ctx, String token) {
  HttpClientRequest get = HttpClientLegacy.get(httpClient, port, "localhost", "/testb/1", res1 -> {
    Buffer resBuf = Buffer.buffer();
    res1.handler(resBuf::appendBuffer);
    res1.endHandler(res2 -> {
      ctx.response().setStatusCode(res1.statusCode());
      ctx.response().end(resBuf);
    });
  });
  get.putHeader("X-Okapi-Token", token);
  get.end();
}
 
Example 9
Source File: APIGatewayVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
/**
 * Dispatch the request to the downstream REST layers.
 *
 * @param context routing context instance
 * @param path    relative path
 * @param client  relevant HTTP client
 */
private void doDispatch(RoutingContext context, String path, HttpClient client, Future<Object> cbFuture) {
  HttpClientRequest toReq = client
    .request(context.request().method(), path, response -> {
      response.bodyHandler(body -> {
        if (response.statusCode() >= 500) { // api endpoint server error, circuit breaker should fail
          cbFuture.fail(response.statusCode() + ": " + body.toString());
        } else {
          HttpServerResponse toRsp = context.response()
            .setStatusCode(response.statusCode());
          response.headers().forEach(header -> {
            toRsp.putHeader(header.getKey(), header.getValue());
          });
          // send response
          toRsp.end(body);
          cbFuture.complete();
        }
        ServiceDiscovery.releaseServiceObject(discovery, client);
      });
    });
  // set headers
  context.request().headers().forEach(header -> {
    toReq.putHeader(header.getKey(), header.getValue());
  });
  if (context.user() != null) {
    toReq.putHeader("user-principal", context.user().principal().encode());
  }
  // send request
  if (context.getBody() == null) {
    toReq.end();
  } else {
    toReq.end(context.getBody());
  }
}
 
Example 10
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testOkFormDataSimpleNotRequiredWithoutParam(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/not/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("", body.toString());
            async.complete();
        });
    });
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end();
}
 
Example 11
Source File: ChainingAuthTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testD(TestContext context) {
    Async async = context.async();
    
    HttpClientRequest req = httpClient.get(TEST_PORT, TEST_HOST, "/test", response -> {
    	context.assertEquals(response.statusCode(), 401);
    	async.complete();
    });
    req.putHeader("Authorization", D_BASIC_AUTH);
    req.end();
}
 
Example 12
Source File: BasicAuthTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testBasicAuthDummyOk(TestContext context) {
    Async async = context.async();
    
    HttpClientRequest req = httpClient.get(TEST_PORT, TEST_HOST, "/dummy", response -> {
    	context.assertEquals(response.statusCode(), 200);
    	async.complete();
    });
    req.putHeader("Authorization", DUMMY_BASIC_AUTH);
    req.end();
    
}
 
Example 13
Source File: BasicAuthTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testBasicAuthDummyKoBadCredentials(TestContext context) {
    Async async = context.async();
    
    HttpClientRequest req = httpClient.get(TEST_PORT, TEST_HOST, "/dummy", response -> {
    	context.assertEquals(response.statusCode(), 401);
    	String header = response.getHeader("WWW-Authenticate");
        context.assertNotNull(header);
     	context.assertEquals("Basic realm=\"vertx-web\"", header);
        async.complete();
    });
    req.putHeader("Authorization", ALL_BASIC_AUTH);
    req.end();
}
 
Example 14
Source File: BasicAuthTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000)
public void testBasicAuthAllOk(TestContext context) {
    Async async = context.async();
    
    HttpClientRequest req = httpClient.get(TEST_PORT, TEST_HOST, "/test", response -> {
    	context.assertEquals(response.statusCode(), 200);
    	async.complete();
    });
    req.putHeader("Authorization", ALL_BASIC_AUTH);
    req.end();
    
}
 
Example 15
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testKoFormDataSimpleRequired(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 400);
            async.complete();
        });
    });
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end();
}
 
Example 16
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testKoFormDataSimpleRequiredWithEmptyValue(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 400);
            async.complete();
        });
    });
    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataRequired=");
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 17
Source File: DemoRamlRestTest.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
/**
 * for POST
 */
private void postData(TestContext context, String url, Buffer buffer, int errorCode, HttpMethod method, String contenttype, String tenant, boolean userIdHeader) {
  Exception stacktrace = new RuntimeException();  // save stacktrace for async handler
  Async async = context.async();
  HttpClient client = vertx.createHttpClient();
  HttpClientRequest request = client.requestAbs(method, url);

  request.exceptionHandler(error -> {
    async.complete();
    System.out.println(" ---------------xxxxxx-------------------- " + error.getMessage());
    context.fail(new RuntimeException(error.getMessage(), stacktrace));
  }).handler(response -> {
    int statusCode = response.statusCode();
    // is it 2XX
    log.info(statusCode + ", " + errorCode + " expected status at "
      + System.currentTimeMillis() + " " + method.name() + " " + url);

    response.bodyHandler(responseData -> {
      if (statusCode == errorCode) {
        final String str = response.getHeader("Content-type");
        if (str == null && statusCode >= 400) {
          context.fail(new RuntimeException("No Content-Type", stacktrace));
        }
        if (statusCode == 422) {
          if (str.contains("application/json")) {
            context.assertTrue(true);
          } else {
            context.fail(new RuntimeException(
              "422 response code should contain a Content-Type header of application/json",
              stacktrace));
          }
        } else if (statusCode == 201) {
          if (userIdHeader) {
            String date = (String) new JsonPathParser(responseData.toJsonObject()).getValueAt("metadata.createdDate");
            if (date == null) {
              context.fail(new RuntimeException(
                "metaData schema createdDate missing from returned json", stacktrace));
            }
          }
        }
        context.assertTrue(true);
      } else {
        System.out.println(" ---------------xxxxxx-1------------------- " + responseData.toString());

        context.fail(new RuntimeException("got unexpected response code, expected: "
          + errorCode + ", received code: " + statusCode + " " + method.name() + " " + url
          + "\ndata:" + responseData.toString(), stacktrace));
      }
      if (!async.isCompleted()) {
        async.complete();
      }
    });
  });
  request.setChunked(true);
  request.putHeader("X-Okapi-Request-Id", "999999999999");
  if(tenant != null){
    request.putHeader("x-okapi-tenant", tenant);
  }
  request.putHeader("Accept", "application/json,text/plain");
  if(userIdHeader){
    request.putHeader("X-Okapi-User-Id", "af23adf0-61ba-4887-bf82-956c4aae2260");
  }
  request.putHeader("Content-type",  contenttype);
  if(buffer != null){
    request.write(buffer);
  }
  request.end();
  async.await();
}
 
Example 18
Source File: DemoRamlRestTest.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
private void testStream(TestContext context, boolean chunk) {
  int chunkSize = 1024;
  int numberChunks = 50;
  Async async = context.async();
  HttpClient httpClient = vertx.createHttpClient();
  HttpClientRequest req = httpClient.post(port, "localhost", "/rmbtests/testStream", res -> {
    Buffer resBuf = Buffer.buffer();
    res.handler(resBuf::appendBuffer);
    res.endHandler(x -> {
      context.assertEquals(200, res.statusCode());
      JsonObject jo = new JsonObject(resBuf);
      context.assertTrue(jo.getBoolean("complete"));
      async.complete();
    });
    res.exceptionHandler(x -> {
      if (!async.isCompleted()) {
        context.assertTrue(false, "exceptionHandler res: " + x.getLocalizedMessage());
        async.complete();
      }
    });
  });
  req.exceptionHandler(x -> {
    if (!async.isCompleted()) {
      context.assertTrue(false, "exceptionHandler req: " + x.getLocalizedMessage());
      async.complete();
    }
  });
  if (chunk) {
    req.setChunked(true);
  } else {
    req.putHeader("Content-Length", Integer.toString(chunkSize * numberChunks));
  }
  req.putHeader("Accept", "application/json,text/plain");
  req.putHeader("Content-type", "application/octet-stream");
  req.putHeader("x-okapi-tenant", TENANT);
  Buffer buf = Buffer.buffer(chunkSize);
  for (int i = 0; i < chunkSize; i++) {
    buf.appendString("X");
  }
  for (int i = 0; i < numberChunks; i++) {
    req.write(buf);
  }
  req.end();
}
 
Example 19
Source File: WebSocketServiceLoginTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void loginPopulatesJWTPayloadWithRequiredValues(final TestContext context) {
  final Async async = context.async();
  final HttpClientRequest request =
      httpClient.post(
          websocketConfiguration.getPort(),
          websocketConfiguration.getHost(),
          "/login",
          response -> {
            response.bodyHandler(
                buffer -> {
                  final String body = buffer.toString();
                  assertThat(body).isNotBlank();

                  final JsonObject respBody = new JsonObject(body);
                  final String token = respBody.getString("token");

                  final JsonObject jwtPayload = decodeJwtPayload(token);
                  assertThat(jwtPayload.getString("username")).isEqualTo("user");
                  assertThat(jwtPayload.getJsonArray("permissions"))
                      .isEqualTo(
                          new JsonArray(
                              list(
                                  "fakePermission",
                                  "eth:blockNumber",
                                  "eth:subscribe",
                                  "web3:*")));
                  assertThat(jwtPayload.getString("privacyPublicKey"))
                      .isEqualTo("A1aVtMxLCUHmBVHXoZzzBgPbW/wj5axDpW9X8l91SGo=");
                  assertThat(jwtPayload.containsKey("iat")).isTrue();
                  assertThat(jwtPayload.containsKey("exp")).isTrue();
                  final long tokenExpiry = jwtPayload.getLong("exp") - jwtPayload.getLong("iat");
                  assertThat(tokenExpiry).isEqualTo(MINUTES.toSeconds(5));

                  async.complete();
                });
          });
  request.putHeader("Content-Type", "application/json; charset=utf-8");
  request.end("{\"username\":\"user\",\"password\":\"pegasys\"}");

  async.awaitSuccess(VERTX_AWAIT_TIMEOUT_MILLIS);
}
 
Example 20
Source File: HttpProvider.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Collection<DynamicProperty>> get() {
    CompletableFuture<Buffer> future = new VertxCompletableFuture<>(vertx);

    URI requestUri = URI.create(dpConfiguration.getUrl());
    boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme());

    final HttpClientOptions options = new HttpClientOptions()
            .setSsl(ssl)
            .setTrustAll(true)
            .setMaxPoolSize(1)
            .setKeepAlive(false)
            .setTcpKeepAlive(false)
            .setConnectTimeout(2000);

    final HttpClient httpClient = vertx.createHttpClient(options);

    final int port = requestUri.getPort() != -1 ? requestUri.getPort() :
            (HTTPS_SCHEME.equals(requestUri.getScheme()) ? 443 : 80);

    try {
        HttpClientRequest request = httpClient.request(
                HttpMethod.GET,
                port,
                requestUri.getHost(),
                requestUri.toString()
        );

        request.putHeader(HttpHeaders.USER_AGENT, NodeUtils.userAgent(node));
        request.putHeader("X-Gravitee-Request-Id", RandomString.generate());

        request.handler(response -> {
            if (response.statusCode() == HttpStatusCode.OK_200) {
                response.bodyHandler(buffer -> {
                    future.complete(buffer);

                    // Close client
                    httpClient.close();
                });
            } else {
                future.complete(null);
            }
        });

        request.exceptionHandler(event -> {
            try {
                future.completeExceptionally(event);

                // Close client
                httpClient.close();
            } catch (IllegalStateException ise) {
                // Do not take care about exception when closing client
            }
        });

        request.end();
    } catch (Exception ex) {
        logger.error("Unable to look for dynamic properties", ex);
        future.completeExceptionally(ex);
    }

    return future.thenApply(buffer -> {
        if (buffer == null) {
            return null;
        }
        return mapper.map(buffer.toString());
    });
}