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


Java AsyncHttpClient類代碼示例

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


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

示例1: testJobSidelining_ShouldSidelineJobsAfter404s

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
@Test
public void testJobSidelining_ShouldSidelineJobsAfter404s() throws Exception {
    /* Creating legit job */
    AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob1", "http://localhost:11000/test", TestConstants.ONE_SECOND)));
    final ListenableFuture<Response> futureResponse = request.execute();
    final Response response = futureResponse.get();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);

    /* Creating Job that is destined to be sidelined*/
    AsyncHttpClient.BoundRequestBuilder request2 = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request2.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob2", "http://localhost:11000/test/404", TestConstants.ONE_SECOND)));
    final ListenableFuture<Response> futureResponseForRequest2 = request2.execute();
    final Response response2 = futureResponseForRequest2.get();
    assertThat(response2.getStatusCode()).isEqualTo(HttpStatus.SC_OK);

    Thread.sleep(5 * TestConstants.ONE_SECOND + 100l);
    testApiCounter.assertHeard("test", 5); // Legit job executed 5 times in 5 seconds
    testApiCounter.assertHeard("test404", 3); // Doomed job executed just thrice
    final Iterable<Job> allJobs = repository.findAll();
    assertThat(allJobs).extracting(Job::getName).containsExactly("testJob1","testJob2");
    assertThat(allJobs).extracting("sideLined",Boolean.class).containsExactly(false,true);
}
 
開發者ID:flipkart-incubator,項目名稱:simpleJobScheduler,代碼行數:24,代碼來源:JobControllerIntegrationTest.java

示例2: AsyncHttpClientHelper

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
/**
 * Constructor that gives you maximum control over configuration and behavior.
 *
 * @param builder
 *     The builder that will create the {@link #asyncHttpClient} and execute all the async downstream HTTP
 *     requests.
 * @param performSubSpanAroundDownstreamCalls
 *     Pass in true to have a distributed tracing subspan added to each downstream call to measure the time spent
 *     on the downstream call, false if you do not want subspans performed. The subspans can be used to determine
 *     how much time is spent processing in your app vs. waiting for downstream requests.
 */
public AsyncHttpClientHelper(AsyncHttpClientConfig.Builder builder, boolean performSubSpanAroundDownstreamCalls) {
    this.performSubSpanAroundDownstreamCalls = performSubSpanAroundDownstreamCalls;

    Map<String, String> mdcContextMap = MDC.getCopyOfContextMap();
    Deque<Span> distributedTraceStack = null;

    try {
        // We have to unlink tracing and MDC from the current thread before we setup the async http client library,
        //      otherwise all the internal threads it uses to do its job will be attached to the current thread's
        //      trace/MDC info forever and always.
        distributedTraceStack = Tracer.getInstance().unregisterFromThread();
        MDC.clear();
        AsyncHttpClientConfig cf = builder.build();
        asyncHttpClient = new AsyncHttpClient(cf);
    }
    finally {
        // Reattach the original tracing and MDC before we leave
        if (mdcContextMap == null)
            MDC.clear();
        else
            MDC.setContextMap(mdcContextMap);

        Tracer.getInstance().registerWithThread(distributedTraceStack);
    }
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:37,代碼來源:AsyncHttpClientHelper.java

示例3: doHttpLog

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
protected static void doHttpLog(String baseDomain, AsyncHttpClient httpClient, long viewerId, String metric,
		String referrer, String url, String location, String productId, String videoId, String uuid, long orderId) {
	String logUrl = baseDomain + buildLogQueryString(metric, uuid, viewerId,location, referrer, url, productId, videoId, orderId);
	
	if(debug){
		if(metric.equals(ORDER)){
			System.out.println("====> ORDER "+logUrl);	
		} else if(metric.equals(CLICK)){
			System.out.println("==> CLICK "+logUrl);	
		} else {
			System.out.println("=> PAGEVIEW "+logUrl);
		}
	}
	
	httpClient.prepareGet(logUrl).execute();
}
 
開發者ID:rfxlab,項目名稱:vidsell-data-simulator,代碼行數:17,代碼來源:VidsellDataSimulatorBot.java

示例4: main

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
public static void main(String[] args) throws IOException {
	initHttpClientPool();
	for (int i = 0; i < 100; i++) {
		try {
			String url = "https://log.rfxlab.com/ping";
			AsyncHttpClient ramdomAsyncHttpClient = getRamdomAsyncHttpClient();
			String ua = ramdomAsyncHttpClient.getConfig().getUserAgent();
			
			Future<Response> f = ramdomAsyncHttpClient.prepareGet(url).execute();
			Response r = f.get();
			System.out.println(ua + " => " +r.getResponseBody());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	System.out.println("done");
	shutdownAllHttpClientPools();
}
 
開發者ID:rfxlab,項目名稱:vidsell-data-simulator,代碼行數:20,代碼來源:BotHttpClientUtil.java

示例5: newNettyAsyncHttpClient

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
public static AsyncHttpClient newNettyAsyncHttpClient(final int timeout, final PoolConfig poolConfig) {

        final NettyConnectionsPool pool = new NettyConnectionsPool( //
                poolConfig.getMaxTotalConnections(),                //
                poolConfig.getMaxNrConnectionsPerHost(),            //
                poolConfig.getMaxIdleTime(),                        //
                poolConfig.getMaxConnectionLifetime(),              //
                false,                                              //
                new HashedWheelTimer());

        final AsyncHttpClientConfig config =
            new AsyncHttpClientConfig.Builder().setConnectionTimeoutInMs(timeout)                                     //
                                               .setRequestTimeoutInMs(timeout)                                        //
                                               .setMaximumConnectionsPerHost(poolConfig.getMaxNrConnectionsPerHost()) //
                                               .setConnectionsPool(pool)                                              //
                                               .build();

        return new AsyncHttpClient(config);
    }
 
開發者ID:vosmann,項目名稱:flechette,代碼行數:20,代碼來源:Clients.java

示例6: testUnsidelining_ShouldUnsidelineGivenJob_AndRunAsPerSchedule

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
@Test
public void testUnsidelining_ShouldUnsidelineGivenJob_AndRunAsPerSchedule() throws Exception {
    /* Creating Job that is destined to be sidelined*/
    AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob2", "http://localhost:11000/test/404", TestConstants.ONE_SECOND)));
    final ListenableFuture<Response> futureResponseForRequest = request.execute();
    final Response response = futureResponseForRequest.get();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);

    Thread.sleep(4 * TestConstants.ONE_SECOND + 100l);
    testApiCounter.assertHeard("test404", 3); // Doomed job executed just thrice
    final List<Job> allJobs = repository.findAll();
    assertThat(allJobs).extracting("sideLined", Boolean.class).containsExactly(true); // asserting job is sidelined

    AsyncHttpClient.BoundRequestBuilder requestUnSideline = asyncHttpClient.preparePut("http://localhost:11000/jobs/testJob2/unsideline").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    final ListenableFuture<Response> unsidelineResponse = requestUnSideline.execute();
    assertThat(unsidelineResponse.get().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    assertThat((repository.findByName("testJob2").isSidelined())).isFalse(); // This check should happen within 3 seconds of the job being unsidelined. Mostly we are good

}
 
開發者ID:flipkart-incubator,項目名稱:simpleJobScheduler,代碼行數:21,代碼來源:JobControllerIntegrationTest.java

示例7: waitForNumQueuesToBePresent

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
public static void waitForNumQueuesToBePresent(int numQueues, AsyncHttpClient httpClient, String rabbitAdminPort) throws Exception {
    for (int i = 1; i <= CONNECTION_MAX_ATTEMPT; i++) {
        try {
            List<String> queueNames = getQueueNames(httpClient, rabbitAdminPort);
            if (queueNames.size()==numQueues) {
                log.infoWithParams("Correct number of queues found.", "numQueues", queueNames.size(), "expected", numQueues, "names", queueNames);
                break;
            }else{
                log.infoWithParams("Wrong number of queues found.", "numQueues", queueNames.size(), "expected", numQueues, "names", queueNames);
                Thread.sleep(CONNECTION_BACKOFF_TIME);
            }
        } catch (Exception ignored) {
            log.infoWithParams("Failed to create connection.. will try again ", "attempt", i, "max-attempts", CONNECTION_MAX_ATTEMPT);
            Thread.sleep(CONNECTION_BACKOFF_TIME);
            if (i == CONNECTION_MAX_ATTEMPT) {
                throw ignored;
            }
        }
    }
}
 
開發者ID:meltwater,項目名稱:rxrabbit,代碼行數:21,代碼來源:RabbitTestUtils.java

示例8: setup

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
@Before
public void setup() throws Exception {
    dockerContainers.rabbit().assertUp();
    rabbitTcpPort = dockerContainers.rabbit().tcpPort();
    rabbitAdminPort = dockerContainers.rabbit().adminPort();
    log.infoWithParams("****** Rabbit broker is up and running *****");

    BrokerAddresses addresses = new BrokerAddresses("amqp://localhost:" + rabbitTcpPort);
    channelFactory = new DefaultChannelFactory(addresses, connectionSettings);
    consumerFactory = new DefaultConsumerFactory(channelFactory, consumeSettings);
    publisherFactory = new DefaultPublisherFactory(channelFactory, publishSettings);
    httpClient = new AsyncHttpClient();

    messagesSeen.clear();
    createQueues(channelFactory, inputQueue, new Exchange(inputExchange));
    publisher = publisherFactory.createPublisher();
    RxJavaHooks.setOnIOScheduler(null);
}
 
開發者ID:meltwater,項目名稱:rxrabbit,代碼行數:19,代碼來源:RxRabbitTests.java

示例9: setup

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
@Before
public void setup() throws Exception {
    dockerContainers.resetAll(false);
    dockerContainers.rabbit(RABBIT_1).assertUp();
    dockerContainers.rabbit(RABBIT_2).assertUp();

    String rabbitTcpPort = dockerContainers.rabbit(RABBIT_1).tcpPort();
    rabbitAdminPort = dockerContainers.rabbit(RABBIT_1).adminPort();
    String rabbit2TcpPort = dockerContainers.rabbit(RABBIT_2).tcpPort();
    log.infoWithParams("****** Rabbit brokers are up and running *****");

    BrokerAddresses addresses = new BrokerAddresses(
            "amqp://localhost:" + rabbitTcpPort + "," +
                    "amqp://localhost:" + rabbit2TcpPort
    );

    channelFactory = new DefaultChannelFactory(addresses, connectionSettings);
    consumerFactory = new DefaultConsumerFactory(channelFactory, consumeSettings);
    DefaultPublisherFactory publisherFactory = new DefaultPublisherFactory(channelFactory, publishSettings);
    httpClient = new AsyncHttpClient();

    messagesSeen.clear();
    createQueues(channelFactory, inputQueue, new Exchange(inputExchange));
    publisher = publisherFactory.createPublisher();
}
 
開發者ID:meltwater,項目名稱:rxrabbit,代碼行數:26,代碼來源:RxRabbitMultiNodeTest.java

示例10: getAsyncRequestBuilder

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
private AsyncHttpClient.BoundRequestBuilder getAsyncRequestBuilder(AsyncHttpClient client, Map<String, String> queryString, String... paths) {
    String target = config.getServerName();
    if (config.getServerPort() != 80) {
        target = target + ":" + config.getServerPort();
    }
    for (String path : paths) {
        target += path;
    }
    AsyncHttpClient.BoundRequestBuilder requestBuilder = client.preparePost(target);

    for (String key : queryString.keySet()) {
        requestBuilder.addQueryParameter(key, queryString.get(key));
    }
    requestBuilder.addHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);
    return requestBuilder;
}
 
開發者ID:viant,項目名稱:jdsunit,代碼行數:17,代碼來源:DsUnitClientImpl.java

示例11: HttpWorker

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
/**
 * Instantiates a new http worker.
 *
 * @param actorMaxOperationTimeoutSec the actor max operation timeout sec
 * @param client the client
 * @param requestUrl the request url
 * @param httpMethod the http method
 * @param postData the post data
 * @param httpHeaderMap the http header map
 * @param responseHeaderMeta the response header meta
 */
public HttpWorker(final int actorMaxOperationTimeoutSec,
        final AsyncHttpClient client, final String requestUrl,
        final HttpMethod httpMethod, final String postData,
        final Map<String, String> httpHeaderMap,
        final ResponseHeaderMeta responseHeaderMeta

) {
    this.actorMaxOperationTimeoutSec = actorMaxOperationTimeoutSec;
    this.client = client;
    this.requestUrl = requestUrl;
    this.httpMethod = httpMethod;
    this.postData = postData;
    if (httpHeaderMap != null)
        this.httpHeaderMap.putAll(httpHeaderMap);
    this.responseHeaderMeta = responseHeaderMeta;

}
 
開發者ID:eBay,項目名稱:parallec,代碼行數:29,代碼來源:HttpWorker.java

示例12: OperationWorker

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
/**
 * Instantiates a new operation worker.
 *
 * @param request
 *            the request
 * @param client
 *            the client
 * @param httpPollerProcessor
 *            the http poller processor
 */
public OperationWorker(final TaskRequest request,
        final AsyncHttpClient client,
        final HttpPollerProcessor httpPollerProcessor) {
    super();

    this.client = client;
    this.request = request;
    /**
     * 20130917: change to add uniform target node capability
     */
    this.trueTargetNode = (request.getHostUniform() == null) ? request
            .getHost() : request.getHostUniform();

    // if needs poller; init
    if (request.isPollable()) {
        pollerData = new PollerData();
        this.httpPollerProcessor = httpPollerProcessor;
        logger.info("Request is Pollable: poller info: "
                + httpPollerProcessor.toString());
    }

}
 
開發者ID:eBay,項目名稱:parallec,代碼行數:33,代碼來源:OperationWorker.java

示例13: MiosUnitConnector

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
/**
 * @param unit
 *            The host to connect to. Give a reachable hostname or IP address, without protocol or port
 */
public MiosUnitConnector(MiosUnit unit, MiosBinding binding) {
	logger.debug("Constructor: unit '{}', binding '{}'", unit, binding);

	this.unit = unit;
	this.binding = binding;

	Builder builder = new AsyncHttpClientConfig.Builder();
	builder.setRequestTimeoutInMs(unit.getTimeout());

	// Use the JDK Provider for now, we're not looking for server-level
	// scalability, and we'd like to lighten the load for folks wanting to
	// run atop RPi units.
	this.client = new AsyncHttpClient(new JDKAsyncHttpProvider(builder.build()));

	pollCall = new LongPoll();
	pollThread = new Thread(pollCall);
}
 
開發者ID:andrey-desman,項目名稱:openhab-hdl,代碼行數:22,代碼來源:MiosUnitConnector.java

示例14: shouldParseParams

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
@Test
public void shouldParseParams() throws Exception {
    // Given
    final ProviderClient providerClient = new ProviderClient(mock(PactConfiguration.class), mock(AsyncHttpClient.class));
    final String queryString = "q=someValue&some=otherValue";
    final Request request = mock(Request.class);
    final Option option = mock(Option.class);

    when(request.query()).thenReturn(option);
    when(option.isEmpty()).thenReturn(false);
    when(option.get()).thenReturn(queryString);

    // When
    final List<Param> params = providerClient.parseParams(request);

    // Then
    assertThat(params.size(), is(2));
    assertThat(params.get(0), is(new Param("q", "someValue")));
    assertThat(params.get(1), is(new Param("some", "otherValue")));
}
 
開發者ID:otto-de,項目名稱:pact-jvm-provider-generic,代碼行數:21,代碼來源:ProviderClientTest.java

示例15: shouldNotFailWithoutParams

import com.ning.http.client.AsyncHttpClient; //導入依賴的package包/類
@Test
public void shouldNotFailWithoutParams() throws Exception {
    // Given
    final ProviderClient providerClient = new ProviderClient(mock(PactConfiguration.class), mock(AsyncHttpClient.class));
    final Request request = mock(Request.class);
    final Option option = mock(Option.class);

    when(request.query()).thenReturn(option);
    when(option.isEmpty()).thenReturn(true);

    // When
    final List<Param> params = providerClient.parseParams(request);

    // Then
    assertThat(params, is(empty()));
}
 
開發者ID:otto-de,項目名稱:pact-jvm-provider-generic,代碼行數:17,代碼來源:ProviderClientTest.java


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