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

The following examples show how to use io.vertx.core.http.HttpClientRequest#write() . 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: RESTJerseyClientTests.java    From vxms with Apache License 2.0 6 votes vote down vote up
@Test
public void stringPOST() throws InterruptedException, ExecutionException {
  HttpClientOptions options = new HttpClientOptions();
  options.setDefaultPort(PORT);
  options.setDefaultHost(HOST);
  HttpClient client = vertx.createHttpClient(options);

  HttpClientRequest request =
      client
          .post(
              "/wsService/stringPOST",
              resp -> {
                resp.exceptionHandler(error -> {});

                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      testComplete();
                    });
              })
          .putHeader("content-length", String.valueOf("hello".getBytes().length))
          .putHeader("Content-Type", "application/json;charset=UTF-8");
  request.write("hello");
  request.end();
  await();
}
 
Example 2
Source File: RESTJerseyMimeTypeClientTests.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Test
public void stringPOSTResponse_1() throws InterruptedException {
  HttpClientOptions options = new HttpClientOptions();
  options.setDefaultPort(PORT);
  options.setDefaultHost(HOST);
  HttpClient client = vertx.createHttpClient(options);

  HttpClientRequest request =
      client
          .post(
              "/wsService/stringPOSTConsumesResponse/123",
              resp -> {
                resp.exceptionHandler(error -> {});

                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      assertEquals(body.toString(), "hello");
                      testComplete();
                    });
              })
          .putHeader("content-length", String.valueOf("hello".getBytes().length))
          .putHeader("Content-Type", "application/json;charset=UTF-8");
  request.write("hello");
  request.end();
  await();
}
 
Example 3
Source File: RESTJerseyMimeTypeClientTests.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Test
public void stringPOSTResponse_2() throws InterruptedException {
  HttpClientOptions options = new HttpClientOptions();
  options.setDefaultPort(PORT);
  options.setDefaultHost(HOST);
  HttpClient client = vertx.createHttpClient(options);

  HttpClientRequest request =
      client
          .post(
              "/wsService/stringPOSTConsumesResponse/123",
              resp -> {
                resp.exceptionHandler(error -> {});

                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      assertEquals(
                          body.toString(),
                          "<html><body><h1>Resource not found</h1></body></html>");
                      testComplete();
                    });
              })
          .putHeader("content-length", String.valueOf("hello".getBytes().length))
          .putHeader("Content-Type", MediaType.APPLICATION_ATOM_XML);
  request.write("hello");
  request.end();
  await();
}
 
Example 4
Source File: RESTJerseyMimeTypeClientTests.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Test
public void stringPOSTResponse_3() throws InterruptedException {
  HttpClientOptions options = new HttpClientOptions();
  options.setDefaultPort(PORT);
  options.setDefaultHost(HOST);
  HttpClient client = vertx.createHttpClient(options);

  HttpClientRequest request =
      client
          .post(
              "/wsService/stringPOSTConsumesResponse/123",
              resp -> {
                resp.exceptionHandler(error -> {});

                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      assertEquals(body.toString(), "hello");
                      testComplete();
                    });
              })
          .putHeader("content-length", String.valueOf("hello".getBytes().length))
          .putHeader("Content-Type", MediaType.APPLICATION_XML);
  request.write("hello");
  request.end();
  await();
}
 
Example 5
Source File: RESTJerseyClientTests.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Test
public void stringPOSTResponse() throws InterruptedException, ExecutionException {

  HttpClientOptions options = new HttpClientOptions();
  options.setDefaultPort(PORT);
  options.setDefaultHost(HOST);
  HttpClient client = vertx.createHttpClient(options);

  HttpClientRequest request =
      client
          .post(
              "/wsService/stringPOSTResponse",
              resp -> {
                resp.exceptionHandler(error -> {});

                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      assertEquals(body.toString(), "hello");
                      testComplete();
                    });
              })
          .putHeader("content-length", String.valueOf("hello".getBytes().length))
          .putHeader("Content-Type", "application/json;charset=UTF-8");
  request.write("hello");
  request.end();
  await();
}
 
Example 6
Source File: RESTJerseyClientTests.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Test
public void stringPUTResponse() throws InterruptedException, ExecutionException {

  HttpClientOptions options = new HttpClientOptions();
  options.setDefaultPort(PORT);
  options.setDefaultHost(HOST);
  HttpClient client = vertx.createHttpClient(options);

  HttpClientRequest request =
      client
          .put(
              "/wsService/stringPUTResponse",
              resp -> {
                resp.exceptionHandler(error -> {});

                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      assertEquals(body.toString(), "hello");
                      testComplete();
                    });
              })
          .putHeader("content-length", String.valueOf("hello".getBytes().length))
          .putHeader("Content-Type", "application/json;charset=UTF-8");
  request.write("hello");
  request.end();
  await();
}
 
Example 7
Source File: RESTJerseyClientTests.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Test
public void stringPOSTResponseWithParameter() throws InterruptedException, ExecutionException {
  HttpClientOptions options = new HttpClientOptions();
  options.setDefaultPort(PORT);
  options.setDefaultHost(HOST);
  HttpClient client = vertx.createHttpClient(options);

  HttpClientRequest request =
      client
          .post(
              "/wsService/stringPOSTResponseWithParameter/123",
              resp -> {
                resp.exceptionHandler(error -> {});

                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      assertEquals(body.toString(), "hello:123");
                      testComplete();
                    });
              })
          .putHeader("content-length", String.valueOf("hello".getBytes().length))
          .putHeader("Content-Type", "application/json;charset=UTF-8");
  request.write("hello");
  request.end();
  await();
}
 
Example 8
Source File: VertxHttpClient.java    From feign-vertx with Apache License 2.0 4 votes vote down vote up
/**
 * Executes HTTP request and returns {@link Future} with response.
 *
 * @param request  request
 * @return future of HTTP response
 */
public Future<Response> execute(final Request request) {
  checkNotNull(request, "Argument request must be not null");

  final HttpClientRequest httpClientRequest;

  try {
    httpClientRequest = makeHttpClientRequest(request);
  } catch (final MalformedURLException unexpectedException) {
    return Future.failedFuture(unexpectedException);
  }

  final Future<Response> responseFuture = Future.future();

  httpClientRequest.exceptionHandler(responseFuture::fail);
  httpClientRequest.handler(response -> {
    final Map<String, Collection<String>> responseHeaders = StreamSupport
        .stream(response.headers().spliterator(), false)
        .collect(Collectors.groupingBy(
            Map.Entry::getKey,
            Collectors.mapping(
                Map.Entry::getValue,
                Collectors.toCollection(ArrayList::new))));

    response.exceptionHandler(responseFuture::fail);
    response.bodyHandler(body -> {
      final Response feignResponse = Response.create(
          response.statusCode(),
          response.statusMessage(),
          responseHeaders,
          body.getBytes());
      responseFuture.complete(feignResponse);
    });
  });

  /* Write body if exists */
  if (request.body() != null) {
    httpClientRequest.write(Buffer.buffer(request.body()));
  }

  httpClientRequest.end();

  return responseFuture;
}
 
Example 9
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 10
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();
}