本文整理汇总了Java中io.reactivex.netty.protocol.http.client.HttpClientResponse类的典型用法代码示例。如果您正苦于以下问题:Java HttpClientResponse类的具体用法?Java HttpClientResponse怎么用?Java HttpClientResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpClientResponse类属于io.reactivex.netty.protocol.http.client包,在下文中一共展示了HttpClientResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: emmit
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
private void emmit(FlowableEmitter<Message> emitter, String roomId) throws Exception {
SSLContext sslCtx = SSLContext.getDefault();
SSLEngine sslEngine = sslCtx.createSSLEngine("stream.gitter.im", 443);
sslEngine.setUseClientMode(true);
HttpClient
.newClient("stream.gitter.im", 443)
.secure(sslEngine)
.createGet("/v1/rooms/" + roomId + "/chatMessages")
.addHeader("Authorization", "Bearer 3cd4820adf59b6a7116f99d92f68a1b786895ce7")
.flatMap(HttpClientResponse::getContent)
.filter(bb -> bb.capacity() > 2)
.map(MessageEncoder::mapToMessage)
.doOnNext(m -> System.out.println("Log Emit: " + m))
.subscribe(emitter::onNext, emitter::onError, emitter::onComplete);
}
示例2: testConcurrentPatch
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@Test
public void testConcurrentPatch() throws InterruptedException {
HttpClientRequest<ByteBuf, ByteBuf> post = post(100L);
Observable<byte[]> slowContent = Observable.just("hello ".getBytes()).repeat()
.zipWith(Observable.interval(50, TimeUnit.MILLISECONDS).startWith(0L), (data, nop) -> data).take(10);
Observable<byte[]> fastContent = Observable.just("goodbye ".getBytes()).repeat()
.zipWith(Observable.interval(10, TimeUnit.MILLISECONDS).startWith(0L), (data, nop) -> data).take(10);
Iterator<HttpClientResponse<ByteBuf>> iterator = post.map(this::getLocation)
.flatMap(location -> Observable.merge(
patch(location, 0 , slowContent),
patch(location, 0, fastContent).delay(120, TimeUnit.MILLISECONDS)))
.toBlocking().getIterator();
// the first response should be the failure
assertThat(iterator.next()).isNotNull()
.extracting(HttpClientResponse::getStatus).containsExactly(HttpResponseStatus.BAD_REQUEST);
// the second one should be sucessfull
assertThat(iterator.next()).isNotNull()
.extracting(HttpClientResponse::getStatus).containsExactly(HttpResponseStatus.NO_CONTENT);
}
示例3: buildEventStream
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
protected static Observable<JsonNode> buildEventStream(String buildId, String lastEventId) {
AtomicReference<String> _lastBuildEventId = new AtomicReference<>(null);
HttpClientRequest<ByteBuf, ByteBuf> request = HTTP_CLIENT
.createGet("/build-export/v1/build/" + buildId + "/events?eventTypes=" + EventProcessor.EVENT_TYPES)
.setKeepAlive(true);
if (BASIC_AUTH != null) {
request = request.addHeader("Authorization", "Basic " + BASIC_AUTH);
}
if (lastEventId != null) {
request = request.addHeader("Last-Event-ID", lastEventId);
}
return request
.flatMap(HttpClientResponse::getContentAsServerSentEvents)
.doOnNext(serverSentEvent -> _lastBuildEventId.set(serverSentEvent.getEventIdAsString()))
.doOnSubscribe(() -> LOGGER.info("Streaming events for build: " + buildId))
.filter(serverSentEvent -> serverSentEvent.getEventTypeAsString().equals("BuildEvent"))
.map(Application::parse)
.onErrorResumeNext(t -> {
LOGGER.info("Error streaming build events of build " + buildId + ", resuming from event id" + _lastBuildEventId.get() + "...");
return buildEventStream(buildId, _lastBuildEventId.get());
});
}
示例4: newHttpClient
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@Override
public HttpClient<ByteBuf, ByteBuf> newHttpClient(final IClientConfig config) {
final List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = new ArrayList<>();
listeners.add(createBearerHeaderAdder());
final PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> pipelineConfigurator = new PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>,
HttpClientRequest<ByteBuf>>(new HttpClientPipelineConfigurator<ByteBuf, ByteBuf>(),
new HttpObjectAggregationConfigurator(maxChunkSize));
final LoadBalancingHttpClient<ByteBuf, ByteBuf> client = LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder()
.withClientConfig(config)
.withExecutorListeners(listeners)
.withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config))
.withPipelineConfigurator(pipelineConfigurator)
.withPoolCleanerScheduler(RibbonTransport.poolCleanerScheduler)
.build();
return client;
}
示例5: getPactUrlsNotFound
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void getPactUrlsNotFound() throws InterruptedException {
HttpClientResponse<ByteBuf> urlsNotFoundResponse = mock(HttpClientResponse.class);
when(urlsNotFoundResponse.getContent()).thenReturn(null);
when(urlsNotFoundResponse.getStatus()).thenReturn(HttpResponseStatus.NOT_FOUND);
HttpResponseHeaders httpResponseHeaders = mock(HttpResponseHeaders.class);
when(httpResponseHeaders.entries()).thenReturn(newArrayList());
when(urlsNotFoundResponse.getHeaders()).thenReturn(httpResponseHeaders);
when(rxClient.submit(any(RxClient.ServerInfo.class), any(HttpClientRequest.class)))
.thenReturn(Observable.just(urlsNotFoundResponse));
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
pactsAggregator.aggregateNodes().toBlocking().subscribe(testSubscriber);
testSubscriber.assertNoErrors();
List<Node> nodes = testSubscriber.getOnNextEvents();
assertThat(nodes).isEmpty();
verify(publisher).publishEvent(any(SystemEvent.class));
}
示例6: onErrorWhenGettingNodeOne
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void onErrorWhenGettingNodeOne() {
HttpClientResponse<ByteBuf> urlsResponse = mock(HttpClientResponse.class);
ByteBuf byteBuf = (new PooledByteBufAllocator()).directBuffer();
ByteBufUtil.writeUtf8(byteBuf, onePactSource);
when(urlsResponse.getContent()).thenReturn(Observable.just(byteBuf));
when(urlsResponse.getStatus()).thenReturn(HttpResponseStatus.OK);
when(rxClient.submit(any(RxClient.ServerInfo.class), any(HttpClientRequest.class)))
.thenReturn(Observable.just(urlsResponse), Observable.error(new RuntimeException()));
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
pactsAggregator.aggregateNodes().toBlocking().subscribe(testSubscriber);
testSubscriber.assertError(RuntimeException.class);
verify(publisher).publishEvent(any(SystemEvent.class));
}
示例7: attemptToReadErrorResponse
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
/**
* Attempts to read the content of an error response as {@code text/plain;charset=utf-8}, otherwise the content
* will be ignored and a string detailing the Content-Type that was not processed.
* <p>
* <b>NOTE:</b>
* <i>
* This method MUST be called from the netty-io thread otherwise the content of the response will not be
* available because if will be released automatically as soon as the netty-io thread is left.
* </i>
* @param resp The response to attempt to read from
* @return An {@link Observable} representing the {@code text/plain;charset=utf-8} response content if it existed
* or an error message indicating the content-type that was not attempted to read.
*/
@NotNull
static Observable<String> attemptToReadErrorResponse(@NotNull final HttpClientResponse<ByteBuf> resp) {
final HttpResponseHeaders headers = resp.getHeaders();
final String contentType = resp.getHeaders().get(HttpHeaderNames.CONTENT_TYPE);
if (headers.isContentLengthSet() && headers.getContentLength() > 0 ) {
if (contentType != null && contentType.startsWith("text/plain")) {
return resp.getContent()
.map(r -> r.toString(StandardCharsets.UTF_8));
} else {
resp.ignoreContent();
final String errMsg = getErrMsg(contentType);
return Observable.just(errMsg);
}
} else {
return Observable.just("");
}
}
示例8: attemptToReadErrorResponse_responseContentIgnoredByDefaultWhenNotString
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@Test
public void attemptToReadErrorResponse_responseContentIgnoredByDefaultWhenNotString() throws Exception {
final String errMsg = "lies";
final byte[] bytes = errMsg.getBytes(StandardCharsets.UTF_8);
final HttpClientResponse<ByteBuf> resp = response(Unpooled.copiedBuffer(bytes), (headers) -> {
headers.add("Content-Type", "application/json;charset=utf-8");
headers.add("Content-Length", bytes.length);
});
final String err = ResponseUtils.attemptToReadErrorResponse(resp).toBlocking().first();
assertThat(err).isNotEqualTo("lies");
try {
resp.getContent().toBlocking().first();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).isEqualTo("Content stream is already disposed.");
}
}
示例9: testMesosStreamIdIsSavedForSuccessfulSubscribeCall
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@Test
public void testMesosStreamIdIsSavedForSuccessfulSubscribeCall() throws Exception {
final AtomicReference<String> mesosStreamId = new AtomicReference<>(null);
final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
"Subscribe",
mesosStreamId,
StringMessageCodec.UTF8_STRING.mediaType()
);
final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
nettyResponse.headers().add("Mesos-Stream-Id", "streamId");
nettyResponse.headers().add("Content-Type", StringMessageCodec.UTF8_STRING.mediaType());
final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
nettyResponse,
UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
);
f.call(response);
assertThat(mesosStreamId.get()).isEqualTo("streamId");
}
示例10: testMesosStreamIdIsNotSavedForUnsuccessfulSubscribeCall
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@Test
public void testMesosStreamIdIsNotSavedForUnsuccessfulSubscribeCall() throws Exception {
final AtomicReference<String> mesosStreamId = new AtomicReference<>(null);
final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
"Subscribe",
mesosStreamId,
StringMessageCodec.UTF8_STRING.mediaType()
);
final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
nettyResponse.headers().add("Mesos-Stream-Id", "streamId");
nettyResponse.headers().add("Content-Type", StringMessageCodec.UTF8_STRING.mediaType());
final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
nettyResponse,
UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
);
try {
f.call(response);
} catch (Mesos4xxException e) {
// expected
}
assertThat(mesosStreamId.get()).isEqualTo(null);
}
示例11: testVerifyResponseOk_ensuresContentTypeOfResponseMatchesReceiveCodec
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@Test
public void testVerifyResponseOk_ensuresContentTypeOfResponseMatchesReceiveCodec() throws Exception {
final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
"Subscribe",
new AtomicReference<>(),
StringMessageCodec.UTF8_STRING.mediaType()
);
final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
nettyResponse.headers().add("Content-Type", "text/html");
final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
nettyResponse,
UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
);
try {
f.call(response);
} catch (MesosException e) {
final String expected = String.format(
"Response had Content-Type \"%s\" expected \"%s\"",
"text/html",
StringMessageCodec.UTF8_STRING.mediaType()
);
assertThat(e.getContext().getMessage()).isEqualTo(expected);
}
}
示例12: newHttpClient
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
@Override
public HttpClient<ByteBuf, ByteBuf> newHttpClient(final IClientConfig config) {
final List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = new ArrayList<>();
listeners.add(createBearerHeaderAdder());
final PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> pipelineConfigurator = new PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>,
HttpClientRequest<ByteBuf>>(new HttpClientPipelineConfigurator<ByteBuf, ByteBuf>(),
new HttpObjectAggregationConfigurator(maxChunkSize));
final LoadBalancingHttpClient<ByteBuf, ByteBuf> client = LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder()
.withClientConfig(config)
.withExecutorListeners(listeners)
.withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config))
.withPipelineConfigurator(pipelineConfigurator)
.withPoolCleanerScheduler(RibbonTransport.poolCleanerScheduler)
.build();
return client;
}
示例13: execute
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
public void execute(IndicesExistsRequest request, final ActionListener<IndicesExistsResponse> listener) {
logger.debug("indices exists request {}", request);
try {
RequestUriBuilder uriBuilder = new RequestUriBuilder(Strings.arrayToCommaDelimitedString(request.indices()));
uriBuilder.addQueryParameter("local", request.local());
uriBuilder.addIndicesOptions(request);
indicesAdminClient.getHttpClient().submit(HttpClientRequest.<ByteBuf>create(HttpMethod.HEAD, uriBuilder.toString()))
.flatMap(HANDLES_404)
.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<IndicesExistsResponse>>() {
@Override
public Observable<IndicesExistsResponse> call(final HttpClientResponse<ByteBuf> response) {
return IndicesExistsResponse.parse(response.getStatus().code());
}
})
.single()
.subscribe(new ListenerCompleterObserver<>(listener));
} catch (Exception e) {
listener.onFailure(e);
}
}
示例14: execute
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
public void execute(ClearScrollRequest request, final ActionListener<ClearScrollResponse> listener) {
logger.debug("clear scroll request {}", request);
try {
RequestUriBuilder uriBuilder = new RequestUriBuilder()
.addEndpoint("_search/scroll");
uriBuilder.addQueryParameter("scroll_id", Strings.collectionToCommaDelimitedString(request.getScrollIds()));
httpClient.getHttpClient().submit(HttpClientRequest.createDelete(uriBuilder.toString()))
.flatMap(HANDLES_404)
.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ClearScrollResponse>>() {
@Override
public Observable<ClearScrollResponse> call(final HttpClientResponse<ByteBuf> response) {
return response.getContent().flatMap(new Func1<ByteBuf, Observable<ClearScrollResponse>>() {
@Override
public Observable<ClearScrollResponse> call(ByteBuf byteBuf) {
return ClearScrollResponse.parse(response.getStatus().code());
}
});
}
})
.single()
.subscribe(new ListenerCompleterObserver<>(listener));
} catch (Exception e) {
listener.onFailure(e);
}
}
示例15: withBookkeeping
import io.reactivex.netty.protocol.http.client.HttpClientResponse; //导入依赖的package包/类
/**
* Utility function to map an Observable<ByteBuf> to an Observable<Integer> while also
* updating our counters for metrics sent and errors.
*/
protected Func1<HttpClientResponse<ByteBuf>, Integer> withBookkeeping(final int batchSize) {
return new Func1<HttpClientResponse<ByteBuf>, Integer>() {
@Override
public Integer call(HttpClientResponse<ByteBuf> response) {
boolean ok = response.getStatus().code() == HTTP_OK;
if (ok) {
numMetricsSent.increment(batchSize);
} else {
LOGGER.info("Status code: {} - Lost {} metrics",
response.getStatus().code(), batchSize);
numMetricsDroppedHttpErr.increment(batchSize);
}
return batchSize;
}
};
}