當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpClientRequest類代碼示例

本文整理匯總了Java中io.vertx.core.http.HttpClientRequest的典型用法代碼示例。如果您正苦於以下問題:Java HttpClientRequest類的具體用法?Java HttpClientRequest怎麽用?Java HttpClientRequest使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpClientRequest類屬於io.vertx.core.http包,在下文中一共展示了HttpClientRequest類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: refreshMembers

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
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();
    });
  }
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:23,代碼來源:ConfigCenterClient.java

示例2: createRequest

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
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;
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:21,代碼來源:VertxHttpMethod.java

示例3: testCreateRequest

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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);
  }
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:27,代碼來源:TestVertxHttpMethod.java

示例4: testSetCseContext

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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);
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:27,代碼來源:TestVertxHttpMethod.java

示例5: asyncPostStringWithData

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
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);
    }
 
開發者ID:Leibnizhu,項目名稱:AlipayWechatPlatform,代碼行數:23,代碼來源:NetworkUtils.java

示例6: requestBegin

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@Override
public Map<HttpClientMetrics, ?> requestBegin(Map<HttpClientMetrics, ?> endpointMetric,
                                              Map<HttpClientMetrics, ?> socketMetric,
                                              SocketAddress localAddress, SocketAddress remoteAddress,
                                              HttpClientRequest request) {
    return null;
}
 
開發者ID:unbroken-dome,項目名稱:vertx-spring,代碼行數:8,代碼來源:DispatchingHttpClientMetrics.java

示例7: proxyUserRequest

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
/**
 * 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());
}
 
開發者ID:travelaudience,項目名稱:nexus-proxy,代碼行數:29,代碼來源:NexusHttpProxy.java

示例8: test404Response

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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);
}
 
開發者ID:gentics,項目名稱:mesh,代碼行數:20,代碼來源:MeshRestAPITest.java

示例9: updateCredentials

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
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;
    }
 
開發者ID:eclipse,項目名稱:hono,代碼行數:24,代碼來源:CredentialsRestServerTest.java

示例10: testOkQueryArrayMulti

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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());
}
 
開發者ID:phiz71,項目名稱:vertx-swagger,代碼行數:19,代碼來源:FormParameterExtractorTest.java

示例11: testOkFormDataArrayCsv

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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());
}
 
開發者ID:phiz71,項目名稱:vertx-swagger,代碼行數:18,代碼來源:FormParameterExtractorTest.java

示例12: call

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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();
                }
            });

}
 
開發者ID:pitchpoint-solutions,項目名稱:sfs,代碼行數:24,代碼來源:PutObject.java

示例13: testAdminConfigRendering

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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);

}
 
開發者ID:gentics,項目名稱:mesh,代碼行數:25,代碼來源:AdminGUIEndpointTest.java

示例14: testOkFormDataArraySsv

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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());
}
 
開發者ID:phiz71,項目名稱:vertx-swagger,代碼行數:18,代碼來源:FormParameterExtractorTest.java

示例15: downloadBinaryField

import io.vertx.core.http.HttpClientRequest; //導入依賴的package包/類
@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");
}
 
開發者ID:gentics,項目名稱:mesh,代碼行數:17,代碼來源:MeshRestHttpClientImpl.java


注:本文中的io.vertx.core.http.HttpClientRequest類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。