Java 类io.vertx.core.http.HttpClientRequest 实例源码

项目:incubator-servicecomb-java-chassis    文件:ConfigCenterClient.java   
private void refreshMembers(MemberDiscovery memberDiscovery) {
  if (CONFIG_CENTER_CONFIG.getAutoDiscoveryEnabled()) {
    String configCenter = memberDiscovery.getConfigServer();
    IpPort ipPort = NetUtils.parseIpPortFromURI(configCenter);
    clientMgr.findThreadBindClientPool().runOnContext(client -> {
      HttpClientRequest request = client.get(ipPort.getPort(), ipPort.getHostOrIp(), URIConst.MEMBERS, rsp -> {
        if (rsp.statusCode() == HttpResponseStatus.OK.code()) {
          rsp.bodyHandler(buf -> {
            memberDiscovery.refreshMembers(buf.toJsonObject());
          });
        }
      });
      SignRequest signReq = createSignRequest(request.method().toString(),
          configCenter + URIConst.MEMBERS, new HashMap<>(), null);
      if (ConfigCenterConfig.INSTANCE.getToken() != null) {
        request.headers().add("X-Auth-Token", ConfigCenterConfig.INSTANCE.getToken());
      }
      authHeaderProviders.forEach(provider -> request.headers().addAll(provider.getSignAuthHeaders(signReq)));
      request.end();
    });
  }
}
项目:incubator-servicecomb-java-chassis    文件:VertxHttpMethod.java   
HttpClientRequest createRequest(HttpClient client, Invocation invocation, IpPort ipPort, String path,
    AsyncResponse asyncResp) {
  URIEndpointObject endpoint = (URIEndpointObject) invocation.getEndpoint().getAddress();
  RequestOptions requestOptions = new RequestOptions();
  requestOptions.setHost(ipPort.getHostOrIp())
      .setPort(ipPort.getPort())
      .setSsl(endpoint.isSslEnabled())
      .setURI(path);

  HttpMethod method = getMethod(invocation);
  LOGGER.debug("Sending request by rest, method={}, qualifiedName={}, path={}, endpoint={}.",
      method,
      invocation.getMicroserviceQualifiedName(),
      path,
      invocation.getEndpoint().getEndpoint());
  HttpClientRequest request = client.request(method, requestOptions, response -> {
    handleResponse(invocation, response, asyncResp);
  });
  return request;
}
项目:incubator-servicecomb-java-chassis    文件:TestVertxHttpMethod.java   
@Test
public void testCreateRequest() {
  HttpClient client = mock(HttpClient.class);
  Invocation invocation = mock(Invocation.class);
  OperationMeta operationMeta = mock(OperationMeta.class);
  Endpoint endpoint = mock(Endpoint.class);
  URIEndpointObject address = mock(URIEndpointObject.class);
  when(invocation.getEndpoint()).thenReturn(endpoint);
  when(endpoint.getAddress()).thenReturn(address);
  when(address.isSslEnabled()).thenReturn(false);
  when(invocation.getOperationMeta()).thenReturn(operationMeta);
  RestOperationMeta swaggerRestOperation = mock(RestOperationMeta.class);
  when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(swaggerRestOperation);
  IpPort ipPort = mock(IpPort.class);
  when(ipPort.getPort()).thenReturn(10);
  when(ipPort.getHostOrIp()).thenReturn("ever");
  AsyncResponse asyncResp = mock(AsyncResponse.class);
  List<HttpMethod> methods = new ArrayList<>(
      Arrays.asList(HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PATCH));
  for (HttpMethod method : methods) {
    when(swaggerRestOperation.getHttpMethod()).thenReturn(method.toString());
    HttpClientRequest obj =
        VertxHttpMethod.INSTANCE.createRequest(client, invocation, ipPort, "good", asyncResp);
    Assert.assertNull(obj);
  }
}
项目:incubator-servicecomb-java-chassis    文件:TestVertxHttpMethod.java   
@Test
public void testSetCseContext() {
  boolean status = false;
  try {
    Invocation invocation = mock(Invocation.class);
    HttpClientResponse httpResponse = mock(HttpClientResponse.class);
    OperationMeta operationMeta = mock(OperationMeta.class);
    RestOperationMeta swaggerRestOperation = mock(RestOperationMeta.class);
    HttpClientRequest request = mock(HttpClientRequest.class);

    Endpoint endpoint = mock(Endpoint.class);
    when(invocation.getOperationMeta()).thenReturn(operationMeta);
    URLPathBuilder urlPathBuilder = mock(URLPathBuilder.class);
    when(swaggerRestOperation.getPathBuilder()).thenReturn(urlPathBuilder);
    operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
    when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(swaggerRestOperation);
    when(invocation.getEndpoint()).thenReturn(endpoint);
    String contentType = httpResponse.getHeader("Content-Type");
    ProduceProcessor produceProcessor = mock(ProduceProcessor.class);
    when(swaggerRestOperation.findProduceProcessor(contentType)).thenReturn(produceProcessor);
    this.setCseContext(invocation, request);
  } catch (Exception ex) {
    status = true;
  }
  Assert.assertFalse(status);
}
项目:AlipayWechatPlatform    文件:NetworkUtils.java   
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);
    }
项目:vertx-spring    文件:DispatchingHttpClientMetrics.java   
@Override
public Map<HttpClientMetrics, ?> requestBegin(Map<HttpClientMetrics, ?> endpointMetric,
                                              Map<HttpClientMetrics, ?> socketMetric,
                                              SocketAddress localAddress, SocketAddress remoteAddress,
                                              HttpClientRequest request) {
    return null;
}
项目:nexus-proxy    文件:NexusHttpProxy.java   
/**
 * Proxies the specified HTTP request, enriching its headers with authentication information.
 *
 * @param userId  the ID of the user making the request.
 * @param origReq the original request (i.e., {@link RoutingContext#request()}.
 * @param origRes the original response (i.e., {@link RoutingContext#request()}.
 */
public void proxyUserRequest(final String userId,
                             final HttpServerRequest origReq,
                             final HttpServerResponse origRes) {
    final Handler<HttpClientResponse> proxiedResHandler = proxiedRes -> {
        origRes.setChunked(true);
        origRes.setStatusCode(proxiedRes.statusCode());
        origRes.headers().setAll(proxiedRes.headers());
        proxiedRes.handler(origRes::write);
        proxiedRes.endHandler(v -> origRes.end());
    };

    final HttpClientRequest proxiedReq;
    proxiedReq = httpClient.request(origReq.method(), port, host, origReq.uri(), proxiedResHandler);
    proxiedReq.setChunked(true);
    proxiedReq.headers().add(X_FORWARDED_PROTO, getHeader(origReq, X_FORWARDED_PROTO, origReq.scheme()));
    proxiedReq.headers().add(X_FORWARDED_FOR, getHeader(origReq, X_FORWARDED_FOR, origReq.remoteAddress().host()));
    proxiedReq.headers().addAll(origReq.headers());
    injectRutHeader(proxiedReq, userId);
    origReq.handler(proxiedReq::write);
    origReq.endHandler(v -> proxiedReq.end());
}
项目:mesh    文件:MeshRestAPITest.java   
@Test
public void test404Response() throws Exception {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultHost("localhost");
    options.setDefaultPort(port());

    HttpClient client = Mesh.vertx().createHttpClient(options);
    CompletableFuture<String> future = new CompletableFuture<>();
    HttpClientRequest request = client.request(HttpMethod.POST, "/api/v1/test", rh -> {
        rh.bodyHandler(bh -> {
            future.complete(bh.toString());
        });
    });
    request.end();

    String response = future.get(1, TimeUnit.SECONDS);
    assertTrue("The response string should not contain any html specific characters but it was {" + response + "} ",
            response.indexOf("<") != 0);
}
项目:hono    文件:CredentialsRestServerTest.java   
private static final Future<HttpClientResponse> updateCredentials(final String authId, final String type, final JsonObject requestPayload, final int expectedResult) {

        final Future<HttpClientResponse> result = Future.future();
        final String uri = String.format(TEMPLATE_URI_CREDENTIALS_INSTANCE, authId, type);

        final HttpClientRequest req = vertx.createHttpClient().put(getPort(), HOST, uri)
                .putHeader(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON)
                .handler(response -> {
                    if (response.statusCode() == expectedResult) {
                        result.complete(response);
                    } else {
                        result.fail("update credentials failed, expected status code " + expectedResult + " but got " + response.statusCode());
                    }
                })
                .exceptionHandler(result::fail);

        if (requestPayload == null) {
            req.end();
        } else {
            req.end(requestPayload.encodePrettily());
        }
        return result;
    }
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@Test()
public void testOkQueryArrayMulti(TestContext context) throws UnsupportedEncodingException {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/multi?array_formdata=1&array_formdata=2&array_formdata=3");
    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")).append("&array_formdata=").append(esc.escape("2")).append("&array_formdata=")
            .append(esc.escape("3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@Test()
public void testOkFormDataArrayCsv(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/csv");
    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());
}
项目:sfs    文件:PutObject.java   
@Override
public Observable<HttpClientResponse> call(Void aVoid) {
    return auth.toHttpAuthorization()
            .flatMap(new Func1<String, Observable<HttpClientResponse>>() {
                @Override
                public Observable<HttpClientResponse> call(String s) {
                    ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();
                    HttpClientRequest httpClientRequest =
                            httpClient.put("/openstackswift001/" + accountName + "/" + containerName + "/" + objectName, handler::complete)
                                    .exceptionHandler(handler::fail)
                                    .setTimeout(20000)
                                    .putHeader(AUTHORIZATION, s);
                    for (String entry : headers.keySet()) {
                        httpClientRequest = httpClientRequest.putHeader(entry, headers.get(entry));
                    }
                    httpClientRequest.setChunked(isChunked());
                    httpClientRequest.end(buffer(data));
                    return handler
                            .single();
                }
            });

}
项目:mesh    文件:AdminGUIEndpointTest.java   
@Test
public void testAdminConfigRendering() throws InterruptedException, ExecutionException, TimeoutException {

    HttpClient client = createHttpClient();
    CompletableFuture<String> future = new CompletableFuture<>();
    HttpClientRequest request = client.request(GET, "/mesh-ui/mesh-ui-config.js", rh -> {
        rh.bodyHandler(bh -> {
            if (rh.statusCode() == 200) {
                future.complete(bh.toString());
            } else {
                future.completeExceptionally(new Exception("Status code wrong {" + rh.statusCode() + "}"));
            }
        });
    });
    request.end();

    String response = future.get(10, TimeUnit.SECONDS);
    // String expectedUrl = "localhost:" + port;
    // assertTrue("The meshConfig.js file did not contain the expected url {" + expectedUrl + "} Response {" + response + "}",
    // response.contains(expectedUrl));
    // System.out.println(response);
    assertTrue("The response string should not contain any html specific characters but it was {" + response + "} ", response.indexOf("<") != 0);

}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:mesh    文件:MeshRestHttpClientImpl.java   
@Override
public MeshRequest<NodeDownloadResponse> downloadBinaryField(String projectName, String nodeUuid, String languageTag, String fieldKey,
        ParameterProvider... parameters) {
    Objects.requireNonNull(projectName, "projectName must not be null");
    Objects.requireNonNull(nodeUuid, "nodeUuid must not be null");

    String path = "/" + encodeFragment(projectName) + "/nodes/" + nodeUuid + "/binary/" + fieldKey + getQuery(parameters);
    String uri = getBaseUri() + path;

    MeshBinaryResponseHandler handler = new MeshBinaryResponseHandler(GET, uri);
    HttpClientRequest request = getClient().request(GET, uri, handler);
    authentication.addAuthenticationInformation(request).subscribe(() -> {
        request.headers().add("Accept", "application/json");
    });
    return new MeshHttpRequestImpl<>(request, handler, null, null, authentication, "application/json");
}
项目:georocket    文件:StoreClient.java   
/**
 * <p>Search the GeoRocket data store and return a {@link ReadStream} of
 * merged chunks matching the given criteria.</p>
 * <p>If <code>query</code> is <code>null</code> or empty all chunks from
 * the given <code>layer</code> (and all sub-layers) will be returned. If
 * <code>layer</code> is also <code>null</code> or empty the contents of the
 * whole data store will be returned.</p>
 * <p>The caller is responsible for handling exceptions through
 * {@link ReadStream#exceptionHandler(Handler)}.</p>
 * @param query a search query specifying which chunks to return (may be
 * <code>null</code>)
 * @param layer the name of the layer where to search for chunks recursively
 * (may be <code>null</code>)
 * @param handler a handler that will receive the {@link ReadStream} from
 * which the merged chunks matching the given criteria can be read
 */
public void search(String query, String layer,
    Handler<AsyncResult<ReadStream<Buffer>>> handler) {
  if ((query == null || query.isEmpty()) && (layer == null || layer.isEmpty())) {
    handler.handle(Future.failedFuture("No search query and no layer given. "
        + "Do you really wish to export/query the whole data store? If so, "
        + "set the layer to '/'."));
    return;
  }
  String queryPath = prepareQuery(query, layer);
  HttpClientRequest request = client.get(getEndpoint() + queryPath);
  request.exceptionHandler(t -> handler.handle(Future.failedFuture(t)));
  request.handler(response -> {
    if (response.statusCode() == 404) {
      fail(response, handler, message -> new NoSuchElementException(ClientAPIException.parse(message).getMessage()));
    } else if (response.statusCode() != 200) {
      fail(response, handler);
    } else {
      handler.handle(Future.succeededFuture(response));
    }
  });
  configureRequest(request).end();
}
项目:okapi    文件:OkapiPerformance.java   
public void useItWithPost(TestContext context) {
  Buffer body = Buffer.buffer();
  HttpClientRequest req = httpClient.post(port, "localhost", "/testb", response -> {
    context.assertEquals(200, response.statusCode());
    String headers = response.headers().entries().toString();
    response.handler(x -> {
      body.appendBuffer(x);
    });
    response.endHandler(x -> {
      context.assertEquals("Hello  (XML) Okapi", body.toString());
      declareSample2(context);
    });
  });
  req.headers().add("X-Okapi-Token", okapiToken);
  req.putHeader("X-Okapi-Tenant", okapiTenant);
  req.putHeader("Content-Type", "text/xml");
  req.end("Okapi");
}
项目:df    文件:StreamingClient.java   
public void handshake(HttpClient hc, FileSystem fs) {

        HttpClientRequest request = hc.put(AgentConstant.SERVER_PORT, AgentConstant.SERVER_ADDR, "", resp -> {
            System.out.println("Response: Hand Shake Status Code - " + resp.statusCode());
            System.out.println("Response: Hand Shake Status Message - " + resp.statusMessage());
            if (resp.statusCode() == AgentConstant.RES_SUCCESS) {
                System.out.println("Response: Hand Shake Status - SUCCESSFUL!");

                //check if it is file/folder processing
                if(Files.isDirectory(Paths.get(AgentConstant.FILE_NAME))) {
                    streamFilesDir(hc, fs);
                } else streamFile(hc, fs);
            }
            else System.out.println("Response: Hand Shake Status - FAILED!");
        });
        request.headers().add("DF_PROTOCOL","REGISTER");
        request.headers().add("DF_MODE", AgentConstant.TRANS_MODE);
        request.headers().add("DF_TYPE", "META");
        request.headers().add("DF_TOPIC", AgentConstant.META_TOPIC);
        request.headers().add("DF_FILENAME", AgentConstant.FILE_NAME);
        request.headers().add("DF_FILTER", AgentConstant.FILTER_TYPE);
        request.headers().add("DF_DATA_TRANS", AgentConstant.DATA_TRANS);

        request.end(setMetaData(AgentConstant.FILE_NAME));
    }
项目:statful-client-vertx    文件:HttpClientMetricsImplTest.java   
@Test
public void testUntaggedRequest() {

    SocketAddress socketMetric = mock(SocketAddress.class);
    SocketAddress localAddress = mock(SocketAddress.class);
    SocketAddress remoteAddress = mock(SocketAddress.class);
    HttpClientRequest request = mock(HttpClientRequest.class);
    MultiMap headers = mock(MultiMap.class);

    when(headers.get(eq(Tags.TRACK_HEADER.toString()))).thenReturn(null);
    when(request.headers()).thenReturn(headers);

    HttpRequestMetrics metrics = victim.requestBegin(null, socketMetric, localAddress, remoteAddress, request);

    assertNull(metrics);
}
项目:statful-client-vertx    文件:HttpClientMetricsImplTest.java   
@Test
public void testRequestBegin() {

    SocketAddress socketMetric = mock(SocketAddress.class);
    SocketAddress localAddress = mock(SocketAddress.class);
    SocketAddress remoteAddress = mock(SocketAddress.class);
    HttpClientRequest request = mock(HttpClientRequest.class);
    MultiMap headers = mock(MultiMap.class);

    when(headers.get(eq(Tags.TRACK_HEADER.toString()))).thenReturn("tag");
    when(request.headers()).thenReturn(headers);

    HttpRequestMetrics metrics = victim.requestBegin(null, socketMetric, localAddress, remoteAddress, request);

    assertNotNull(metrics);
    assertEquals(remoteAddress, metrics.getAddress());
}
项目:vertx-swagger    文件:BodyParameterExtractorTest.java   
@Test
public void testOkAddBodyRequiredWithXML(TestContext context) {
    Async async = context.async();
    String bodyReqXml = "<BodyType><id>1</id><name>body 1</name></BodyType>";
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/body/required");
    req.handler(response -> {
        context.assertEquals(response.statusCode(), 200);
        response.bodyHandler(body -> {
            context.assertEquals(bodyReqXml, body.toString());
            async.complete();
        });

    })
    .putHeader(HttpHeaders.CONTENT_TYPE, "application/xml")
    .end(bodyReqXml);
}
项目:okapi    文件:PullManager.java   
private void getList(String urlBase,
  Handler<ExtendedAsyncResult<ModuleDescriptor[]>> fut) {
  String url = urlBase;
  if (!url.endsWith("/")) {
    url += "/";
  }
  url += "_/proxy/modules";
  final Buffer body = Buffer.buffer();
  HttpClientRequest req = httpClient.getAbs(url, res -> {
    res.handler(body::appendBuffer);
    res.endHandler(x -> {
      if (res.statusCode() != 200) {
        fut.handle(new Failure<>(ErrorType.USER, body.toString()));
      } else {
        ModuleDescriptor[] ml = Json.decodeValue(body.toString(),
          ModuleDescriptor[].class);
        fut.handle(new Success<>(ml));
      }
    });
    res.exceptionHandler(x
      -> fut.handle(new Failure<>(ErrorType.INTERNAL, x.getMessage())));
  });
  req.exceptionHandler(x
    -> fut.handle(new Failure<>(ErrorType.INTERNAL, x.getMessage())));
  req.end();
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@Test()
public void testOkFormDataArrayTsv(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/tsv");
    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\t2\t3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
项目:vertx-swagger    文件:BodyParameterExtractorTest.java   
@Test
public void testOkAddArrayBody(TestContext context) {
    Async async = context.async();
    BodyType body1 = new BodyType(1L, "body 1");
    BodyType body2 = new BodyType(2L, "body 2");
    JsonArray bodys = new JsonArray(Arrays.asList(body1, body2));
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/body/array");
    req.handler(response -> {
        context.assertEquals(response.statusCode(), 200);
        response.bodyHandler(body -> {
            context.assertEquals(Json.encode(bodys), body.toString());
            async.complete();
        });

    }).end(Json.encode(bodys));
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@Test()
public void testKoFormDataSimpleFileWithoutFile(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/file");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 400);
            async.complete();
        });
    });
    // Construct multipart data
    req.putHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=MyBoundary");
    req.end();
}
项目:deprecated-mod-metadata    文件:HttpClient.java   
public void put(URL url,
                Object body,
                String tenantId,
                Handler<HttpClientResponse> responseHandler) {

  HttpClientRequest request = client.putAbs(url.toString(), responseHandler);

  request.headers().add("Accept","application/json, text/plain");
  request.headers().add("Content-type","application/json");

  if(tenantId != null) {
    request.headers().add(TENANT_HEADER, tenantId);
  }

  request.end(Json.encodePrettily(body));
}
项目:sfs    文件:PostAccount.java   
@Override
public Observable<HttpClientResponse> call(Void aVoid) {
    return auth.toHttpAuthorization()
            .flatMap(new Func1<String, Observable<HttpClientResponse>>() {
                @Override
                public Observable<HttpClientResponse> call(String s) {
                    ObservableFuture<HttpClientResponse> handler = RxHelper.observableFuture();
                    HttpClientRequest httpClientRequest =
                            httpClient.post("/openstackswift001/" + accountName, handler::complete)
                                    .exceptionHandler(handler::fail)
                                    .setTimeout(10000)
                                    .putHeader(AUTHORIZATION, s);
                    for (String entry : headers.keySet()) {
                        httpClientRequest = httpClientRequest.putHeader(entry, headers.get(entry));
                    }
                    httpClientRequest.end();
                    return handler
                            .single();
                }
            });

}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@Test()
public void testOkFormDataSimpleRequired(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(), 200);
            context.assertEquals("toto", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataRequired=").append(esc.escape("toto"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@Test()
public void testOkFormDataSimpleRequiredAllowEmpty(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required/allowempty");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("", body.toString());
            async.complete();
        });
    });
    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataRequired=");
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
项目:vertx-swagger    文件:FormParameterExtractorTest.java   
@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());
}
项目:incubator-servicecomb-java-chassis    文件:ConfigCenterClient.java   
public void refreshConfig(String configcenter) {
  clientMgr.findThreadBindClientPool().runOnContext(client -> {
    String path = URIConst.ITEMS + "?dimensionsInfo=" + StringUtils.deleteWhitespace(serviceName);
    IpPort ipPort = NetUtils.parseIpPortFromURI(configcenter);
    HttpClientRequest request = client.get(ipPort.getPort(), ipPort.getHostOrIp(), path, rsp -> {
      if (rsp.statusCode() == HttpResponseStatus.OK.code()) {
        rsp.bodyHandler(buf -> {
          try {
            parseConfigUtils
                .refreshConfigItems(JsonUtils.OBJ_MAPPER.readValue(buf.toString(),
                    new TypeReference<LinkedHashMap<String, Map<String, String>>>() {
                    }));
          } catch (IOException e) {
            LOGGER.error("config refresh result parse fail", e);
          }
        });
      } else {
        LOGGER.error("fetch config fail");
      }
    });
    Map<String, String> headers = new HashMap<>();
    headers.put("x-domain-name", tenantName);
    if (ConfigCenterConfig.INSTANCE.getToken() != null) {
      headers.put("X-Auth-Token", ConfigCenterConfig.INSTANCE.getToken());
    }
    request.headers().addAll(headers);
    authHeaderProviders.forEach(provider -> request.headers()
        .addAll(provider.getSignAuthHeaders(createSignRequest(request.method().toString(),
            configcenter + path, headers, null))));
    request.exceptionHandler(e -> {
      LOGGER.error("config refresh fail {}", e.getMessage());
    });
    request.end();
  });
}
项目:incubator-servicecomb-java-chassis    文件:VertxHttpMethod.java   
protected void setCseContext(Invocation invocation, HttpClientRequest request) {
  try {
    String cseContext = JsonUtils.writeValueAsString(invocation.getContext());
    request.putHeader(org.apache.servicecomb.core.Const.CSE_CONTEXT, cseContext);
  } catch (Exception e) {
    LOGGER.debug(e.toString());
  }
}
项目:vertx-spring    文件:DispatchingHttpClientMetrics.java   
@Override
public Map<HttpClientMetrics, ?> responsePushed(Map<HttpClientMetrics, ?> endpointMetric,
                                                Map<HttpClientMetrics, ?> socketMetric,
                                                SocketAddress localAddress, SocketAddress remoteAddress,
                                                HttpClientRequest request) {
    return unmap2WithResult(endpointMetric, socketMetric,
            (m, ec, sc) -> m.responsePushed(ec, sc, localAddress, remoteAddress, request));
}
项目:vertx-spring    文件:VertxActuatorMetrics.java   
@Override
public StopWatch requestBegin(StopWatch endpointWatch, StopWatch socketMetric, SocketAddress localAddress,
                              SocketAddress remoteAddress, HttpClientRequest request) {
    counterService.increment("requests.sent");
    StopWatch requestWatch = new StopWatch();
    requestWatch.start();
    return requestWatch;
}
项目:mod-circulation-storage    文件:HttpClient.java   
public void post(URL url,
                 Object body,
                 String tenantId,
                 String userId,
                 Handler<HttpClientResponse> responseHandler) {

  HttpClientRequest request = client.postAbs(url.toString(), responseHandler);

  request.headers().add("Accept","application/json, text/plain");
  request.headers().add("Content-type","application/json");

  if(tenantId != null) {
    request.headers().add(TENANT_HEADER, tenantId);
  }

  if(userId != null) {
    request.headers().add(USERID_HEADER, userId);
  }

  if(body != null) {
    String encodedBody = Json.encodePrettily(body);

    System.out.println(String.format("POST %s, Request: %s",
      url.toString(), encodedBody));

    log.debug(String.format("POST %s, Request: %s",
      url.toString(), encodedBody));

    request.end(encodedBody);
  }
  else {
    request.end();
  }
}
项目:mod-circulation-storage    文件:HttpClient.java   
public void put(URL url,
                Object body,
                String tenantId,
                String userId,
                Handler<HttpClientResponse> responseHandler) {

  HttpClientRequest request = client.putAbs(url.toString(), responseHandler);

  request.headers().add("Accept","application/json, text/plain");
  request.headers().add("Content-type","application/json");

  if(tenantId != null) {
    request.headers().add(TENANT_HEADER, tenantId);
  }

  if(userId != null){
    request.headers().add(USERID_HEADER, userId);
  }

  String encodedBody = Json.encodePrettily(body);

  System.out.println(String.format("PUT %s, Request: %s",
    url.toString(), encodedBody));

  log.debug(String.format("PUT %s, Request: %s",
    url.toString(), encodedBody));

  request.end(encodedBody);
}
项目:app-ms    文件:VertxClientResponse.java   
@SuppressWarnings({
    "unchecked",
    "rawtypes"
})
public VertxClientResponse(final ClientConfiguration configuration,
    final HttpClientRequest httpClientRequest) {

    super(configuration);
    semaphoredHeaders = new SemaphoredHeaders<>();

    // Used in the base classes
    metadata = semaphoredHeaders;
    is = new VertxBlockingInputStream();

    httpClientRequest.handler(httpClientResponse -> {
        LOG.debug("Status = {}", httpClientResponse.statusCode());
        setStatus(httpClientResponse.statusCode());
        final MultiMap headers = httpClientResponse.headers();
        metadata.putAll((Map) Conversions.toMultivaluedStringMap(headers));
        httpClientResponse.handler(is::populate)
            .endHandler(aVoid -> is.end());
        LOG.trace("prepared HTTP client response handler");

        semaphoredHeaders.releaseLock();
    }).exceptionHandler(e -> {
        LOG.error("exception handling response", e);
        is.error(e);
        exception = e;
        semaphoredHeaders.releaseLock();
    });
    LOG.trace("prepared HTTP client request handler");

}
项目:app-ms    文件:VertxOutputStream.java   
private void addChunkedIfNeeded() {

        if (stream instanceof HttpServerResponse) {
            final HttpServerResponse resp = (HttpServerResponse) stream;
            if (resp.headers().get(HttpHeaders.CONTENT_LENGTH) == null) {
                resp.setChunked(true);
            }
        } else if (stream instanceof HttpClientRequest) {
            final HttpClientRequest req = (HttpClientRequest) stream;
            if (req.headers().get(HttpHeaders.CONTENT_LENGTH) == null) {
                req.setChunked(true);
            }
        }

    }
项目:vertx-prometheus-metrics    文件:PrometheusMetricsTestCase.java   
private @NotNull HttpClientRequest request(@NotNull Handler<Buffer> handler, @NotNull Async latch) {
  return vertx.createHttpClient()
      .get(PORT, "localhost", "/metrics")
      .handler(response -> {
        context.assertEquals(HttpResponseStatus.OK.code(), response.statusCode());
        response.bodyHandler(body -> {
          handler.handle(body);
          latch.complete();
        });
      });
}