• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java HttpClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: httpRespondsEmpty

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void httpRespondsEmpty() {
	NettyContext server =
			HttpServer.create(0)
			          .newRouter(r ->
			              r.post("/test/{param}", (req, res) -> Mono.empty()))
			          .block(Duration.ofSeconds(30));

	HttpClient client =
			HttpClient.create("localhost", server.address().getPort());

	Mono<ByteBuf> content = client
			            .post("/test/World", req -> req.header("Content-Type", "text/plain")
			                                           .sendString(Mono.just("Hello")
			                                           .log("client-send")))
			            .flatMap(res -> res.receive()
			                               .log("client-received")
			                               .next())
			            .doOnError(t -> System.err.println("Failed requesting server: " + t.getMessage()));

	StepVerifier.create(content)
			    .expectComplete()
			    .verify(Duration.ofSeconds(5000));

	server.dispose();
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:27,代码来源:HttpTests.java


示例2: main

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    GuavaCacheMetrics.monitor(registry, guavaCache, "book.guava");

    // read all of Frankenstein
    HttpClient.create("www.gutenberg.org")
        .get("/cache/epub/84/pg84.txt")
        .flatMapMany(res -> res.addHandler(wordDecoder()).receive().asString())
        .delayElements(Duration.ofMillis(10)) // one word per 10 ms
        .filter(word -> !word.isEmpty())
        .doOnNext(word -> {
            if (guavaCache.getIfPresent(word) == null)
                guavaCache.put(word, 1);
        })
        .blockLast();
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:17,代码来源:CacheSample.java


示例3: testChannelInactiveThrowsIOException

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void testChannelInactiveThrowsIOException() throws Exception {
	ExecutorService threadPool = Executors.newCachedThreadPool();

	int abortServerPort = SocketUtils.findAvailableTcpPort();
	ConnectionAbortServer abortServer = new ConnectionAbortServer(abortServerPort);

	threadPool.submit(abortServer);

	if(!abortServer.await(10, TimeUnit.SECONDS)){
		throw new IOException("Fail to start test server");
	}

	Mono<HttpClientResponse> response =
			HttpClient.create(ops -> ops.host("localhost")
			                            .port(abortServerPort))
			          .get("/",
					          req -> req.sendHeaders()
					                    .sendString(Flux.just("a", "b", "c")));

	StepVerifier.create(response)
	            .expectError()
	            .verify();

	abortServer.close();
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:27,代码来源:ChannelOperationsHandlerTest.java


示例4: simpleTest

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void simpleTest() {
	httpServer = HttpServer.create(0)
	                       .newHandler((in, out) -> out.sendWebsocket((i, o) -> o.sendString(
			                       Mono.just("test"))))
	                       .block(Duration.ofSeconds(30));

	String res = HttpClient.create(httpServer.address()
	                                  .getPort())
	                .get("/test",
			                out -> out.addHeader("Authorization", auth)
			                          .sendWebsocket())
	                .flatMapMany(in -> in.receive()
	                                 .asString())
	                .log()
	                .collectList()
	                .block(Duration.ofSeconds(30))
	                .get(0);

	Assert.assertThat(res, is("test"));
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:22,代码来源:WebsocketTest.java


示例5: simpleSubprotocolServerNoSubprotocol

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void simpleSubprotocolServerNoSubprotocol() throws Exception {
	httpServer = HttpServer.create(0)
	                                    .newHandler((in, out) -> out.sendWebsocket((i, o) -> o.sendString(
			                                    Mono.just("test"))))
	                                    .block(Duration.ofSeconds(30));

	StepVerifier.create(
			HttpClient.create(
					httpServer.address().getPort())
			          .get("/test",
					          out -> out.addHeader("Authorization", auth)
					                    .sendWebsocket("SUBPROTOCOL,OTHER"))
			          .flatMapMany(in -> in.receive().asString())
	)
	            .verifyErrorMessage("Invalid subprotocol. Actual: null. Expected one of: SUBPROTOCOL,OTHER");
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:18,代码来源:WebsocketTest.java


示例6: simpleSubprotocolServerNotSupported

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void simpleSubprotocolServerNotSupported() throws Exception {
	httpServer = HttpServer.create(0)
	                       .newHandler((in, out) -> out.sendWebsocket(
			                       "protoA,protoB",
			                       (i, o) -> o.sendString(Mono.just("test"))))
	                       .block(Duration.ofSeconds(30));

	StepVerifier.create(
			HttpClient.create(
					httpServer.address().getPort())
			          .get("/test",
					          out -> out.addHeader("Authorization", auth)
					                    .sendWebsocket("SUBPROTOCOL,OTHER"))
			          .flatMapMany(in -> in.receive().asString())
	)
	            //the SERVER returned null which means that it couldn't select a protocol
	            .verifyErrorMessage("Invalid subprotocol. Actual: null. Expected one of: SUBPROTOCOL,OTHER");
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:20,代码来源:WebsocketTest.java


示例7: simpleSubprotocolServerSupported

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void simpleSubprotocolServerSupported() throws Exception {
	httpServer = HttpServer.create(0)
	                       .newHandler((in, out) -> out.sendWebsocket(
			                       "SUBPROTOCOL",
			                       (i, o) -> o.sendString(
					                       Mono.just("test"))))
	                       .block(Duration.ofSeconds(30));

	String res = HttpClient.create(httpServer.address().getPort())
	                       .get("/test",
			                out -> out.addHeader("Authorization", auth)
			                          .sendWebsocket("SUBPROTOCOL,OTHER"))
	                .flatMapMany(in -> in.receive().asString()).log().collectList().block(Duration.ofSeconds(30)).get(0);

	Assert.assertThat(res, is("test"));
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:18,代码来源:WebsocketTest.java


示例8: simpleSubprotocolSelected

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void simpleSubprotocolSelected() throws Exception {
	httpServer = HttpServer.create(0)
	                       .newHandler((in, out) -> out.sendWebsocket(
			                       "NOT, Common",
			                       (i, o) -> o.sendString(
					                       Mono.just("SERVER:" + o.selectedSubprotocol()))))
	                       .block(Duration.ofSeconds(30));

	String res = HttpClient.create(httpServer.address().getPort())
	                       .get("/test",
			                out -> out.addHeader("Authorization", auth)
			                          .sendWebsocket("Common,OTHER"))
	                       .map(HttpClientResponse::receiveWebsocket)
	                       .flatMapMany(in -> in.receive().asString()
			                       .map(srv -> "CLIENT:" + in.selectedSubprotocol() + "-" + srv))
	                       .log().collectList().block(Duration.ofSeconds(30)).get(0);

	Assert.assertThat(res, is("CLIENT:Common-SERVER:Common"));
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:21,代码来源:WebsocketTest.java


示例9: noSubprotocolSelected

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void noSubprotocolSelected() {
	httpServer = HttpServer.create(0)
	                       .newHandler((in, out) -> out.sendWebsocket((i, o) -> o.sendString(
			                       Mono.just("SERVER:" + o.selectedSubprotocol()))))
	                       .block(Duration.ofSeconds(30));

	String res = HttpClient.create(httpServer.address()
	                                         .getPort())
	                       .get("/test",
			                       out -> out.addHeader("Authorization", auth)
			                                 .sendWebsocket())
	                       .map(HttpClientResponse::receiveWebsocket)
	                       .flatMapMany(in -> in.receive()
	                                        .asString()
	                                        .map(srv -> "CLIENT:" + in.selectedSubprotocol() + "-" + srv))
	                       .log()
	                       .collectList()
	                       .block(Duration.ofSeconds(30))
	                       .get(0);

	Assert.assertThat(res, is("CLIENT:null-SERVER:null"));
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:24,代码来源:WebsocketTest.java


示例10: anySubprotocolSelectsFirstClientProvided

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void anySubprotocolSelectsFirstClientProvided() {
	httpServer = HttpServer.create(0)
	                       .newHandler((in, out) -> out.sendWebsocket("proto2,*", (i, o) -> o.sendString(
			                       Mono.just("SERVER:" + o.selectedSubprotocol()))))
	                       .block(Duration.ofSeconds(30));

	String res = HttpClient.create(httpServer.address()
	                                         .getPort())
	                       .get("/test",
			                       out -> out.addHeader("Authorization", auth)
			                                 .sendWebsocket("proto1, proto2"))
	                       .map(HttpClientResponse::receiveWebsocket)
	                       .flatMapMany(in -> in.receive()
	                                        .asString()
	                                        .map(srv -> "CLIENT:" + in.selectedSubprotocol() + "-" + srv))
	                       .log()
	                       .collectList()
	                       .block(Duration.ofSeconds(30))
	                       .get(0);

	Assert.assertThat(res, is("CLIENT:proto1-SERVER:proto1"));
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:24,代码来源:WebsocketTest.java


示例11: assertSendFile

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
private void assertSendFile(Function<HttpServerResponse, NettyOutbound> fn) {
	NettyContext context =
			HttpServer.create(opt -> opt.host("localhost"))
			          .newHandler((req, resp) -> fn.apply(resp))
			          .block();


	HttpClientResponse response =
			HttpClient.create(opt -> opt.connectAddress(() -> context.address()))
			          .get("/foo")
			          .block(Duration.ofSeconds(120));

	context.dispose();
	context.onClose().block();

	String body = response.receive().aggregate().asString(StandardCharsets.UTF_8).block();

	assertThat(body)
			.startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.")
			.contains("1024 mark here -><- 1024 mark here")
			.endsWith("End of File");
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:23,代码来源:HttpServerTests.java


示例12: errorResponseAndReturn

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void errorResponseAndReturn() throws Exception {
	NettyContext c = HttpServer.create(0)
	                           .newHandler((req, resp) -> Mono.error(new Exception("returnError")))
	                           .block();

	HttpClientResponse res =
			HttpClient.create(c.address().getPort())
			          .get("/return", r -> r.failOnServerError(false))
			          .block();
	assertThat(res.status().code()).isEqualTo(500);
	res.dispose();

	c.dispose();

}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:17,代码来源:HttpServerTests.java


示例13: flushOnComplete

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void flushOnComplete() {

	Flux<String> test = Flux.range(0, 100)
	                        .map(n -> String.format("%010d", n));

	NettyContext c = HttpServer.create(0)
	                           .newHandler((req, resp) -> resp.sendString(test.map(s -> s + "\n")))
	                           .block(Duration.ofSeconds(30));

	Flux<String> client = HttpClient.create(c.address()
	                                         .getPort())
	                                .get("/")
	                                .block(Duration.ofSeconds(30))
	                                .addHandler(new LineBasedFrameDecoder(10))
	                                .receive()
	                                .asString();

	StepVerifier.create(client)
	            .expectNextSequence(test.toIterable())
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));

	c.dispose();
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:26,代码来源:HttpServerTests.java


示例14: startRouter

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void startRouter() {
	BlockingNettyContext facade = HttpServer.create(0)
	                                        .startRouter(routes -> routes.get("/hello",
			                                        (req, resp) -> resp.sendString(Mono.just("hello!"))));

	try {
		HttpClientResponse res =
				HttpClient.create(facade.getPort())
				          .get("/hello")
				          .block();
		assertThat(res.status().code()).isEqualTo(200);
		res.dispose();

		res = HttpClient.create(facade.getPort())
		                .get("/helloMan", req -> req.failOnClientError(false))
		                .block();
		assertThat(res.status().code()).isEqualTo(404);
		res.dispose();
	}
	finally {
		facade.shutdown();
	}
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:25,代码来源:HttpServerTests.java


示例15: testIssue186

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void testIssue186() {
	NettyContext server =
			HttpServer.create(0)
			          .newHandler((req, res) -> res.status(200).send())
			          .block(Duration.ofSeconds(300));

	HttpClient client =
			HttpClient.create(ops -> ops.connectAddress(() -> server.address())
					                    .poolResources(PoolResources.fixed("test", 1)));

	try {
		doTestIssue186(client);
		doTestIssue186(client);
	}
	finally {
		server.dispose();
	}

}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:21,代码来源:HttpServerTests.java


示例16: emmit

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
private void emmit(FluxSink<Message> emitter, String roomId) {
    HttpClient
            .create()
            .get("https://stream.gitter.im/v1/rooms/" + roomId + "/chatMessages",
                    (r) -> r.addHeader("Authorization", "Bearer 3cd4820adf59b6a7116f99d92f68a1b786895ce7"))
            .flatMapMany(HttpClientResponse::receiveContent)
            .map(ByteBufHolder::content)
            .filter(bb -> bb.capacity() > 2)
            .map(MessageEncoder::mapToMessage)
            .doOnNext(m -> System.out.println("Log Emit: " + m))
            .subscribe(emitter::next, emitter::error, emitter::complete);
}
 
开发者ID:OlegDokuka,项目名称:reactive-playing,代码行数:13,代码来源:ReactorGitterClient.java


示例17: doTestPublisherSenderOnCompleteFlushInProgress

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
private void doTestPublisherSenderOnCompleteFlushInProgress(boolean useScheduler) {
	NettyContext server =
			HttpServer.create(0)
			          .newHandler((req, res) ->
			                  req.receive()
			                     .asString()
			                     .doOnNext(System.err::println)
			                     .then(res.status(200).sendHeaders().then()))
			          .block(Duration.ofSeconds(30));

	Flux<String> flux = Flux.range(1, 257).map(count -> count + "");
	if (useScheduler) {
		flux.publishOn(Schedulers.single());
	}
	Mono<HttpClientResponse> client =
			HttpClient.create(server.address().getPort())
			          .post("/", req -> req.sendString(flux));

	StepVerifier.create(client)
	            .expectNextMatches(res -> {
	                res.dispose();
	                return res.status().code() == 200;
	            })
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));

	server.dispose();
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:29,代码来源:ChannelOperationsHandlerTest.java


示例18: testIssue196

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
@Ignore
public void testIssue196() throws Exception {
	ExecutorService threadPool = Executors.newCachedThreadPool();

	int testServerPort = SocketUtils.findAvailableTcpPort();
	TestServer testServer = new TestServer(testServerPort);

	threadPool.submit(testServer);

	if(!testServer.await(10, TimeUnit.SECONDS)){
		throw new IOException("Fail to start test server");
	}

	HttpClient client =
	        HttpClient.create(opt -> opt.port(testServerPort)
	                                    .poolResources(PoolResources.fixed("test", 1)));

	Flux.range(0, 2)
	    .flatMap(i -> client.get("/205")
	                        .flatMap(res -> res.receive()
	                                           .aggregate()
	                                           .asString()))
	    .blockLast(Duration.ofSeconds(100));

	testServer.close();
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:28,代码来源:ChannelOperationsHandlerTest.java


示例19: afterNettyContextInit

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
public void afterNettyContextInit() {
	AtomicInteger readCount = new AtomicInteger();
	ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg)
				throws Exception {
			readCount.incrementAndGet();
			super.channelRead(ctx, msg);
		}
	};
	String handlerName = "test";

	NettyContext nettyContext =
			HttpServer.create(opt -> opt.afterNettyContextInit(c -> c.addHandlerFirst(handlerName, handler)))
			          .start((req, resp) -> resp.sendNotFound())
			          .getContext();

	HttpClientResponse response1 = HttpClient.create(opt -> opt.connectAddress(() -> nettyContext.address()))
	                                         .get("/", req -> req.failOnClientError(false).send())
	                                         .block();

	assertThat(response1.status().code()).isEqualTo(404);
	response1.dispose();

	//the "main" context doesn't get enriched with handlers from options...
	assertThat(nettyContext.channel().pipeline().names()).doesNotContain(handlerName);
	//...but the child channels that are created for requests are
	assertThat(readCount.get()).isEqualTo(1);

	HttpClientResponse response2 = HttpClient.create(opt -> opt.connectAddress(() -> nettyContext.address()))
	                                         .get("/", req -> req.failOnClientError(false).send())
	                                         .block();

	assertThat(response2.status().code()).isEqualTo(404); //reactor handler was applied and produced a response
	response2.dispose();
	assertThat(readCount.get()).isEqualTo(1); //BUT channelHandler wasn't applied a second time since not Shareable

	nettyContext.dispose();
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:41,代码来源:NettyOptionsTest.java


示例20: proxyTest

import reactor.ipc.netty.http.client.HttpClient; //导入依赖的package包/类
@Test
@Ignore
public void proxyTest() throws Exception {
	HttpServer server = HttpServer.create();
	server.newRouter(r -> r.get("/search/{search}",
			(in, out) -> HttpClient.create()
			                       .get("foaas.herokuapp.com/life/" + in.param(
					                       "search"))
			                       .flatMapMany(repliesOut -> out.send(repliesOut.receive()))))
	      .block(Duration.ofSeconds(30))
	      .onClose()
	      .block(Duration.ofSeconds(30));
}
 
开发者ID:reactor,项目名称:reactor-netty,代码行数:14,代码来源:TcpServerTests.java



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java Server类代码示例发布时间:2022-05-22
下一篇:
Java PreDeactivated类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap