当前位置: 首页>>代码示例>>Java>>正文


Java HttpClient类代码示例

本文整理汇总了Java中io.vertx.core.http.HttpClient的典型用法代码示例。如果您正苦于以下问题:Java HttpClient类的具体用法?Java HttpClient怎么用?Java HttpClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


HttpClient类属于io.vertx.core.http包,在下文中一共展示了HttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: hello3

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
@Path("3")
@GET
public void hello3(@Suspended final AsyncResponse asyncResponse,
	      // Inject the Vertx instance
	      @Context Vertx vertx){
	System.err.println("Creating client");
	HttpClientOptions options = new HttpClientOptions();
	options.setSsl(true);
	options.setTrustAll(true);
	options.setVerifyHost(false);
	HttpClient client = vertx.createHttpClient(options);
	client.getNow(443,
			"www.google.com", 
			"/robots.txt", 
			resp -> {
				System.err.println("Got response");
				resp.bodyHandler(body -> {
					System.err.println("Got body");
					asyncResponse.resume(Response.ok(body.toString()).build());
				});
			});
	System.err.println("Created client");
}
 
开发者ID:FroMage,项目名称:redpipe,代码行数:24,代码来源:MyResource.java

示例2: createClientPool

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
@Test
public void createClientPool(@Mocked Vertx vertx, @Mocked Context context, @Mocked HttpClient httpClient) {
  new Expectations(VertxImpl.class) {
    {
      VertxImpl.context();
      result = context;
      context.owner();
      result = vertx;
      vertx.createHttpClient(httpClientOptions);
      result = httpClient;
    }
  };
  HttpClientWithContext pool = factory.createClientPool();

  Assert.assertSame(context, pool.context());
  Assert.assertSame(httpClient, pool.getHttpClient());
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:18,代码来源:TestHttpClientPoolFactory.java

示例3: createRequest

import io.vertx.core.http.HttpClient; //导入依赖的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

示例4: testDoMethodNullPointerException

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
@Test
public void testDoMethodNullPointerException(@Mocked HttpClient httpClient) throws Exception {
  Context context = new MockUp<Context>() {
    @Mock
    public void runOnContext(Handler<Void> action) {
      action.handle(null);
    }
  }.getMockInstance();
  HttpClientWithContext httpClientWithContext = new HttpClientWithContext(httpClient, context);

  Invocation invocation = mock(Invocation.class);
  AsyncResponse asyncResp = mock(AsyncResponse.class);

  try {
    this.doMethod(httpClientWithContext, invocation, asyncResp);
    fail("Expect to throw NullPointerException, but got none");
  } catch (NullPointerException e) {
  }
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:20,代码来源:TestVertxHttpMethod.java

示例5: testCreateRequest

import io.vertx.core.http.HttpClient; //导入依赖的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

示例6: VertxClientEngine

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
public VertxClientEngine(final HttpClient httpClient) {

        try {
            this.httpClient = httpClient;
            sslContext = SSLContext.getDefault();
            hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
        } catch (final NoSuchAlgorithmException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
 
开发者ID:trajano,项目名称:app-ms,代码行数:11,代码来源:VertxClientEngine.java

示例7: testEngineWithInjectedClientPost

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
@Test
public void testEngineWithInjectedClientPost() {

    final HttpClient httpClient = Vertx.vertx().createHttpClient(httpClientOptions);
    final Client client = new ResteasyClientBuilder().httpEngine(new VertxClientEngine(httpClient))
        .register(GsonMessageBodyHandler.class).build();
    final Form xform = new Form();
    xform.param("userName", "ca1\\\\meowmix");
    xform.param("password", "mingnamulan");
    xform.param("state", "authenticate");
    xform.param("style", "xml");
    xform.param("xsl", "none");

    final JsonObject arsString = client.target("https://httpbin.org/post").request()
        .post(Entity.form(xform), JsonObject.class);
    assertEquals("xml", arsString.getAsJsonObject("form").get("style").getAsString());
}
 
开发者ID:trajano,项目名称:app-ms,代码行数:18,代码来源:SpringJaxrsHandlerTest.java

示例8: testEngineWithInjectedClientPost2

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
@Test
public void testEngineWithInjectedClientPost2() {

    final ResteasyDeployment deployment = new ResteasyDeployment();
    deployment.start();
    final ResteasyProviderFactory providerFactory = deployment.getProviderFactory();
    final HttpClient httpClient = Vertx.vertx().createHttpClient(httpClientOptions);
    final Client client = new ResteasyClientBuilder()
        .providerFactory(providerFactory)
        .httpEngine(new VertxClientEngine(httpClient))
        .register(GsonMessageBodyHandler.class)
        .build();
    final Form xform = new Form();
    xform.param("userName", "ca1\\\\meowmix");
    xform.param("password", "mingnamulan");
    xform.param("state", "authenticate");
    xform.param("style", "xml");
    xform.param("xsl", "none");

    final Response response = client.target("https://httpbin.org/post").request(MediaType.APPLICATION_JSON)
        .post(Entity.form(xform), Response.class);
    assertFalse(response.getStringHeaders().isEmpty());
    System.out.println(response.getStringHeaders());
    assertFalse(response.getHeaders().isEmpty());
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType());
    assertTrue(response.hasEntity());
    final JsonObject arsString = response.readEntity(JsonObject.class);
    assertEquals("xml", arsString.getAsJsonObject("form").get("style").getAsString());
}
 
开发者ID:trajano,项目名称:app-ms,代码行数:30,代码来源:SpringJaxrsHandlerTest.java

示例9: getValueForCompany

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
private Future<Double> getValueForCompany(HttpClient client, String company, int numberOfShares) {
    // Create the future object that will  get the value once the value have been retrieved
    Future<Double> future = Future.future();

    client
            .get(root + "/?name=" + encode(company), response -> {
                response.exceptionHandler(future::fail);
                if (response.statusCode() == 200) {
                    response.bodyHandler(buffer -> {
                        double v = numberOfShares * buffer.toJsonObject().getDouble("bid");
                        future.complete(v);
                    });
                } else {
                    future.complete(0.0);
                }
            })
            .exceptionHandler(future::fail)
            .end();

    return future;
}
 
开发者ID:docker-production-aws,项目名称:microtrader,代码行数:22,代码来源:PortfolioServiceImpl.java

示例10: testConfigurationOptions

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
@Test
public void testConfigurationOptions(TestContext testContext) throws Exception {
  final HttpClientOptions options = new HttpClientOptions().setTryUseCompression(false);

  final HttpClient httpClient = runTestOnContext.vertx().createHttpClient(options);

  final Async asyncOp = testContext.async();

  // issue a request on the custom server bind address and port, testing for compression
  httpClient.get(SERVER_PORT, SERVER_BIND_ADDRESS, "/hystrix-dashboard/")
            .setChunked(false)
            .putHeader(HttpHeaders.ACCEPT_ENCODING, HttpHeaders.DEFLATE_GZIP)
            .handler(resp -> {
              testContext.assertEquals(200, resp.statusCode(), "Should have fetched the index page with status 200");
              testContext.assertEquals("gzip", resp.getHeader(HttpHeaders.CONTENT_ENCODING));
            })
            .exceptionHandler(testContext::fail)
            .endHandler(event -> asyncOp.complete())
            .end();
}
 
开发者ID:kennedyoliveira,项目名称:standalone-hystrix-dashboard,代码行数:21,代码来源:HystrixDashboardConfigurationTest.java

示例11: example2

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
public void example2(ServiceDiscovery discovery) {
  // Get the record
  discovery.getRecord(new JsonObject().put("name", "some-http-service"), ar -> {
    if (ar.succeeded() && ar.result() != null) {
      // Retrieve the service reference
      ServiceReference reference = discovery.getReference(ar.result());
      // Retrieve the service object
      HttpClient client = reference.getAs(HttpClient.class);

      // You need to path the complete path
      client.getNow("/api/persons", response -> {

        // ...

        // Dont' forget to release the service
        reference.release();

      });
    }
  });
}
 
开发者ID:vert-x3,项目名称:vertx-service-discovery,代码行数:22,代码来源:HTTPEndpointExamples.java

示例12: example3

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
public void example3(ServiceDiscovery discovery) {
  HttpEndpoint.getClient(discovery, new JsonObject().put("name", "some-http-service"), ar -> {
    if (ar.succeeded()) {
      HttpClient client = ar.result();

      // You need to path the complete path
      client.getNow("/api/persons", response -> {

        // ...

        // Dont' forget to release the service
        ServiceDiscovery.releaseServiceObject(discovery, client);

      });
    }
  });
}
 
开发者ID:vert-x3,项目名称:vertx-service-discovery,代码行数:18,代码来源:HTTPEndpointExamples.java

示例13: testPublicationAndConsumptionWithConfiguration

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
@Test
public void testPublicationAndConsumptionWithConfiguration(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.getClient(discovery, new JsonObject().put("name", "hello-service"), new JsonObject().put
      ("keepAlive", false), found -> {
      context.assertTrue(found.succeeded());
      context.assertTrue(found.result() != null);
      HttpClient client = found.result();
      client.getNow("/foo", response -> {
        context.assertEquals(response.statusCode(), 200);
        context.assertEquals(response.getHeader("connection"), "close");
        response.bodyHandler(body -> {
          context.assertEquals(body.toString(), "hello");
          ServiceDiscovery.releaseServiceObject(discovery, client);
          discovery.unpublish(published.getRegistration(), v -> async.complete());
        });
      });
    });
  });
}
 
开发者ID:vert-x3,项目名称:vertx-service-discovery,代码行数:27,代码来源:HttpEndpointTest.java

示例14: handshake

import io.vertx.core.http.HttpClient; //导入依赖的package包/类
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));
 	}
 
开发者ID:datafibers,项目名称:df,代码行数:26,代码来源:StreamingClient.java

示例15: test404Response

import io.vertx.core.http.HttpClient; //导入依赖的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


注:本文中的io.vertx.core.http.HttpClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。