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


Java Response类代码示例

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


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

示例1: get

import org.asynchttpclient.Response; //导入依赖的package包/类
@SuppressWarnings("NullableProblems")
@Override
public T get(long timeout, TimeUnit unit) throws RestyException {
    Response response;

    try {
        response = future.get(timeout, unit);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        future.abort(e);
        log.error("获取响应失败:{}", e.getMessage());
        if (this.getRestyCommand().isAsyncArg() || this.getRestyCommand().isAsyncReturn()) {
            throw new RestyException(e);
        }
        response = FailedResponse.create(new ConnectionException(e));
    }
    return (T) ResponseConverterContext.DEFAULT.convertResponse(restyCommand, response);
}
 
开发者ID:darren-fu,项目名称:RestyPass,代码行数:18,代码来源:RestyFuture.java

示例2: sendRequest

import org.asynchttpclient.Response; //导入依赖的package包/类
@Override
public <T> Single<T> sendRequest(SqsAction<T> action) {
    Request asyncRequest = action.toHttpRequest(credentialsProvider.getCredentials());
    SingleSubject<T> responseSubject = SingleSubject.create();
    httpClient.executeRequest(asyncRequest, new AsyncCompletionHandler<Response>() {
        @Override
        public Response onCompleted(Response httpResponse) {
            Single.fromCallable(() -> action.parseHttpResponse(httpResponse))
                    .subscribeWith(responseSubject);
            return httpResponse;
        }

        @Override
        public void onThrowable(Throwable throwable) {
            responseSubject.onError(throwable);
        }
    });
    return responseSubject;
}
 
开发者ID:Bandwidth,项目名称:async-sqs,代码行数:20,代码来源:BaseSqsRequestSender.java

示例3: testConvert

import org.asynchttpclient.Response; //导入依赖的package包/类
@Test
public void testConvert() throws IOException {
    Response responseMock = mock(Response.class);

    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(TEST_KEY_A, TEST_VALUE_B);
    headers.add(TEST_KEY_C, TEST_VALUE_D);

    when(responseMock.getHeaders()).thenReturn(headers);
    when(responseMock.getStatusCode()).thenReturn(STATUS_CODE);
    when(responseMock.getStatusText()).thenReturn(STATUS_TEXT);
    when(responseMock.getResponseBodyAsStream()).thenReturn(
            new ByteArrayInputStream(ENCODED_BODY.getBytes(StandardCharsets.UTF_8))
    );

    BiFunction<Response, Request, HttpResponse> converter = new AsyncResponseConverter();
    HttpResponse awsResponse = converter.apply(responseMock, null);

    assertThat(awsResponse.getHeaders().get(TEST_KEY_A)).isEqualTo(TEST_VALUE_B);
    assertThat(awsResponse.getHeaders().get(TEST_KEY_C)).isEqualTo(TEST_VALUE_D);
    assertThat(awsResponse.getStatusCode()).isEqualTo(STATUS_CODE);
    assertThat(awsResponse.getStatusText()).isEqualTo(STATUS_TEXT);
    assertThat(new BufferedReader(new InputStreamReader(awsResponse.getContent())).readLine())
            .isEqualTo(ENCODED_BODY);
}
 
开发者ID:Bandwidth,项目名称:async-sqs,代码行数:26,代码来源:AsyncResponseConverterTest.java

示例4: ResumableAsyncHandler

import org.asynchttpclient.Response; //导入依赖的package包/类
private ResumableAsyncHandler(long byteTransferred, ResumableProcessor resumableProcessor,
        AsyncHandler<Response> decoratedAsyncHandler, boolean accumulateBody) {

    this.byteTransferred = new AtomicLong(byteTransferred);

    if (resumableProcessor == null) {
        resumableProcessor = new NULLResumableHandler();
    }
    this.resumableProcessor = resumableProcessor;

    resumableIndex = resumableProcessor.load();
    resumeIndexThread.addResumableProcessor(resumableProcessor);

    this.decoratedAsyncHandler = decoratedAsyncHandler;
    this.accumulateBody = accumulateBody;
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:17,代码来源:ResumableAsyncHandler.java

示例5: testMaxTotalConnectionsException

import org.asynchttpclient.Response; //导入依赖的package包/类
@Test(groups = "standalone", expectedExceptions = TooManyConnectionsException.class)
public void testMaxTotalConnectionsException() throws Throwable {
    try (AsyncHttpClient client = asyncHttpClient(config().setKeepAlive(true).setMaxConnections(1))) {
        String url = getTargetUrl();

        List<ListenableFuture<Response>> futures = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            logger.info("{} requesting url [{}]...", i, url);
            futures.add(client.prepareGet(url).execute());
        }

        Exception exception = null;
        for (ListenableFuture<Response> future : futures) {
            try {
                future.get();
            } catch (Exception ex) {
                exception = ex;
                break;
            }
        }

        assertNotNull(exception);
        throw exception.getCause();
    }
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:26,代码来源:ConnectionPoolTest.java

示例6: waitForAndAssertResponse

import org.asynchttpclient.Response; //导入依赖的package包/类
private void waitForAndAssertResponse(ListenableFuture<Response> responseFuture) throws InterruptedException, java.util.concurrent.ExecutionException, IOException {
    Response response = responseFuture.get();
    if (500 == response.getStatusCode()) {
        StringBuilder sb = new StringBuilder();
        sb.append("==============\n");
        sb.append("500 response from call\n");
        sb.append("Headers:" + response.getHeaders() + "\n");
        sb.append("==============\n");
        logger.debug(sb.toString());
        assertEquals(response.getStatusCode(), 500, "Should have 500 status code");
        assertTrue(response.getHeader("X-Exception").contains("invalid.chunk.length"), "Should have failed due to chunking");
        fail("HARD Failing the test due to provided InputStreamBodyGenerator, chunking incorrectly:" + response.getHeader("X-Exception"));
    } else {
        assertEquals(response.getResponseBodyAsBytes(), LARGE_IMAGE_BYTES);
    }
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:17,代码来源:ChunkingTest.java

示例7: negativeContentTypeTest

import org.asynchttpclient.Response; //导入依赖的package包/类
@Test(groups = "standalone")
public void negativeContentTypeTest() throws Exception {

    AsyncHttpClientConfig config = config()//
            .setConnectTimeout(100)//
            .setMaxConnections(50)//
            .setRequestTimeout(5 * 60 * 1000) // 5 minutes
            .build();

    try (AsyncHttpClient client = asyncHttpClient(config)) {
        RequestBuilder requestBuilder = post(getTargetUrl())//
                .setHeader("Content-Type", "message/rfc822")//
                .setBody(new InputStreamBodyGenerator(new ByteArrayInputStream(MY_MESSAGE.getBytes())));

        Future<Response> future = client.executeRequest(requestBuilder.build());

        System.out.println("waiting for response");
        Response response = future.get();
        assertEquals(response.getStatusCode(), 200);
        assertEquals(response.getResponseBody(), MY_MESSAGE);
    }
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:23,代码来源:BodyChunkTest.java

示例8: testWildcardNonProxyHosts

import org.asynchttpclient.Response; //导入依赖的package包/类
public void testWildcardNonProxyHosts() throws IOException, ExecutionException, TimeoutException, InterruptedException {
    // FIXME not threadsafe!
    Properties originalProps = new Properties();
    originalProps.putAll(System.getProperties());
    System.setProperty(ProxyUtils.PROXY_HOST, "127.0.0.1");
    System.setProperty(ProxyUtils.PROXY_PORT, String.valueOf(port1));
    System.setProperty(ProxyUtils.PROXY_NONPROXYHOSTS, "127.*");
    AsyncHttpClientConfigHelper.reloadProperties();

    try (AsyncHttpClient client = asyncHttpClient(config().setUseProxyProperties(true))) {
        String nonProxifiedTarget = "http://127.0.0.1:1234/";
        Future<Response> f = client.prepareGet(nonProxifiedTarget).execute();
        try {
            f.get(3, TimeUnit.SECONDS);
            fail("should not be able to connect");
        } catch (ExecutionException e) {
            // ok, no proxy used
        }
    } finally {
        System.setProperties(originalProps);
    }
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:23,代码来源:ProxyTest.java

示例9: getTSUID

import org.asynchttpclient.Response; //导入依赖的package包/类
public String getTSUID(final String metricName, final Map<String, String> tags) {
		final StringBuilder b = new StringBuilder(tsdbUrl)
			.append("/api/uid/tsmeta?m=")
			.append(metricName)
			.append(tags)
			.append("&create=false");
		log.info("Query: [{}]", b.toString());
		//cli.prepareGet("http://pdk-pt-cltsdb-01:4242/api/uid/tsmeta?m=ptms.ti&app=ptms").execute();
//		for(Map.Entry<String, String> tag: tags.entrySet()) {
//			b.append("&").append(tag.getKey()).append("=").append(tag.getValue());
//		}
		final Future<Response> f =  cli.prepareGet(b.toString()).execute();
		try {
			final Response resp = f.get();
			return resp.getResponseBody();
		} catch (Exception ex) {
			log.error("getTSUID failed with URL [{}]", b.toString(), ex);
			throw new RuntimeException(ex);
		}		
	}
 
开发者ID:nickman,项目名称:HeliosStreams,代码行数:21,代码来源:QueryTool.java

示例10: testOnStatusReceivedOkStatusWithDecoratedAsyncHandler

import org.asynchttpclient.Response; //导入依赖的package包/类
@Test
public void testOnStatusReceivedOkStatusWithDecoratedAsyncHandler() throws Exception {
    HttpResponseStatus mockResponseStatus = mock(HttpResponseStatus.class);
    when(mockResponseStatus.getStatusCode()).thenReturn(200);
    when(mockResponseStatus.getUri()).thenReturn(mock(Uri.class));

    @SuppressWarnings("unchecked")
    AsyncHandler<Response> decoratedAsyncHandler = mock(AsyncHandler.class);
    State mockState = mock(State.class);
    when(decoratedAsyncHandler.onStatusReceived(mockResponseStatus)).thenReturn(mockState);

    ResumableAsyncHandler handler = new ResumableAsyncHandler(decoratedAsyncHandler);

    State state = handler.onStatusReceived(mockResponseStatus);
    verify(decoratedAsyncHandler).onStatusReceived(mockResponseStatus);
    assertEquals(state, mockState, "State returned should be equal to the one returned from decoratedAsyncHandler");
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:18,代码来源:ResumableAsyncHandlerTest.java

示例11: testOnBodyPartReceivedWithDecoratedAsyncHandler

import org.asynchttpclient.Response; //导入依赖的package包/类
@Test
public void testOnBodyPartReceivedWithDecoratedAsyncHandler() throws Exception {
    HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
    when(bodyPart.getBodyPartBytes()).thenReturn(new byte[0]);
    ByteBuffer buffer = ByteBuffer.allocate(0);
    when(bodyPart.getBodyByteBuffer()).thenReturn(buffer);

    @SuppressWarnings("unchecked")
    AsyncHandler<Response> decoratedAsyncHandler = mock(AsyncHandler.class);
    State mockState = mock(State.class);
    when(decoratedAsyncHandler.onBodyPartReceived(bodyPart)).thenReturn(mockState);

    // following is needed to set the url variable
    HttpResponseStatus mockResponseStatus = mock(HttpResponseStatus.class);
    when(mockResponseStatus.getStatusCode()).thenReturn(200);
    Uri mockUri = mock(Uri.class);
    when(mockUri.toUrl()).thenReturn("http://non.null");
    when(mockResponseStatus.getUri()).thenReturn(mockUri);

    ResumableAsyncHandler handler = new ResumableAsyncHandler(decoratedAsyncHandler);
    handler.onStatusReceived(mockResponseStatus);

    State state = handler.onBodyPartReceived(bodyPart);
    assertEquals(state, mockState, "State should be equal to the state returned from decoratedAsyncHandler");

}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:27,代码来源:ResumableAsyncHandlerTest.java

示例12: deferredSimple

import org.asynchttpclient.Response; //导入依赖的package包/类
@Test(groups = "standalone")
public void deferredSimple() throws IOException, ExecutionException, TimeoutException, InterruptedException {
    try (AsyncHttpClient client = asyncHttpClient(getAsyncHttpClientConfig())) {
        BoundRequestBuilder r = client.prepareGet("http://localhost:" + port1 + "/deferredSimple");

        CountingOutputStream cos = new CountingOutputStream();
        BodyDeferringAsyncHandler bdah = new BodyDeferringAsyncHandler(cos);
        Future<Response> f = r.execute(bdah);
        Response resp = bdah.getResponse();
        assertNotNull(resp);
        assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
        assertEquals(resp.getHeader("content-length"), String.valueOf(HALF_GIG));
        // we got headers only, it's probably not all yet here (we have BIG file
        // downloading)
        assertTrue(cos.getByteCount() <= HALF_GIG);

        // now be polite and wait for body arrival too (otherwise we would be
        // dropping the "line" on server)
        f.get();
        // it all should be here now
        assertEquals(cos.getByteCount(), HALF_GIG);
    }
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:24,代码来源:BodyDeferringAsyncHandlerTest.java

示例13: markError

import org.asynchttpclient.Response; //导入依赖的package包/类
/**
 * Count and log error, then send error response.
 *
 * @param status  The response status
 * @param response  The druid response
 * @param druidQueryId  The Druid query ID
 * @param error  callback for handling http errors.
 */
private void markError(Status status, Response response, String druidQueryId, HttpErrorCallback error) {
    getHttpErrorMeter().mark();
    LOG.debug(
            "druid {} error: {} {} {} and druid query id: {}",
            getServiceConfig().getNameAndUrl(),
            status.getStatusCode(),
            status.getReasonPhrase(),
            response.getResponseBody(),
            druidQueryId
    );

    error.invoke(
            status.getStatusCode(),
            status.getReasonPhrase(),
            response.getResponseBody()
    );
}
 
开发者ID:yahoo,项目名称:fili,代码行数:26,代码来源:AsyncDruidWebServiceImpl.java

示例14: propFindWebDavTest

import org.asynchttpclient.Response; //导入依赖的package包/类
@Test(groups = "standalone")
public void propFindWebDavTest() throws InterruptedException, IOException, ExecutionException {
    try (AsyncHttpClient c = asyncHttpClient()) {
        Request mkcolRequest = new RequestBuilder("MKCOL").setUrl(getTargetUrl()).build();
        Response response = c.executeRequest(mkcolRequest).get();
        assertEquals(response.getStatusCode(), 201);

        Request putRequest = put(String.format("http://localhost:%s/folder1/Test.txt", port1)).setBody("this is a test").build();
        response = c.executeRequest(putRequest).get();
        assertEquals(response.getStatusCode(), 201);

        Request propFindRequest = new RequestBuilder("PROPFIND").setUrl(String.format("http://localhost:%s/folder1/Test.txt", port1)).build();
        response = c.executeRequest(propFindRequest).get();

        assertEquals(response.getStatusCode(), 207);
        assertTrue(response.getResponseBody().contains("<status>HTTP/1.1 200 OK</status>"));
    }
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:19,代码来源:WebDavBasicTest.java

示例15: markDimensionCacheHealthy

import org.asynchttpclient.Response; //导入依赖的package包/类
/**
 * Makes the dimensions passthrough.
 * <p>
 * This method sends a lastUpdated date to each dimension in the dimension cache, allowing the health checks
 * to pass without having to set up a proper dimension loader. For each dimension, d, the following query is
 * sent to the /v1/cache/dimensions/d endpoint:
 * {
 *     "name": "d",
 *     "lastUpdated": "2016-01-01"
 * }
 *
 * @param port  The port through which we access the webservice
 *
 * @throws IOException If something goes terribly wrong when building the JSON or sending it
 */
private static void markDimensionCacheHealthy(int port) throws IOException {
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    for (DimensionConfig dimensionConfig : new WikiDimensions().getAllDimensionConfigurations()) {
        String dimension = dimensionConfig.getApiName();
        BoundRequestBuilder boundRequestBuilder = asyncHttpClient.preparePost("http://localhost:" + port +
                "/v1/cache/dimensions/" + dimension)
                .addHeader("Content-type", "application/json")
                .setBody(
                        String.format("{\n \"name\":\"%s\",\n \"lastUpdated\":\"2016-01-01\"\n}", dimension)
                );

        ListenableFuture<Response> responseFuture = boundRequestBuilder.execute();
        try {
            Response response = responseFuture.get();
            LOG.debug("Mark Dimension Cache Updated Response: ", response);
        } catch (InterruptedException | ExecutionException e) {
            LOG.warn("Failed while marking dimensions healthy", e);
        }
    }
}
 
开发者ID:yahoo,项目名称:fili,代码行数:36,代码来源:WikiMain.java


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