Java Code Examples for org.asynchttpclient.Response#getResponseBody()

The following examples show how to use org.asynchttpclient.Response#getResponseBody() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CloneWorkFlowTest.java    From blynk-server with GNU General Public License v3.0 7 votes vote down vote up
@Test
public void getProjectByCloneCodeViaHttp() throws Exception {
    clientPair.appClient.send("getCloneCode 1");
    String token = clientPair.appClient.getBody();
    assertNotNull(token);
    assertEquals(32, token.length());

    AsyncHttpClient httpclient = new DefaultAsyncHttpClient(
            new DefaultAsyncHttpClientConfig.Builder()
                    .setUserAgent(null)
                    .setKeepAlive(true)
                    .build()
    );

    Future<Response> f = httpclient.prepareGet("http://localhost:" + properties.getHttpPort() + "/" + token + "/clone").execute();
    Response response = f.get();
    assertEquals(200, response.getStatusCode());
    String responseBody = response.getResponseBody();
    assertNotNull(responseBody);
    DashBoard dashBoard = JsonParser.parseDashboard(responseBody, 0);
    assertEquals("My Dashboard", dashBoard.name);
    httpclient.close();
}
 
Example 2
Source File: IndicesAdminClient.java    From flummi with Apache License 2.0 6 votes vote down vote up
public JsonObject getIndexSettings() {
    try {

        Response response = httpClient.prepareGet("/_all/_settings")
                .addHeader(CONTENT_TYPE, APPL_JSON)
                .execute().get();
        if (response.getStatusCode() != 200) {
            throw RequestBuilderUtil.toHttpServerErrorException(response);
        }
        String jsonString = null;
        jsonString = response.getResponseBody();
        return gson.fromJson(jsonString, JsonObject.class);
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: IndicesAdminClient.java    From flummi with Apache License 2.0 6 votes vote down vote up
public List<String> getAllIndexNames() {
    try {
        Response response = httpClient.prepareGet("/_all")
                .addHeader(CONTENT_TYPE, APPL_JSON)
                .execute().get();
        if (response.getStatusCode() != 200) {
            throw RequestBuilderUtil.toHttpServerErrorException(response);
        }
        String jsonString = response.getResponseBody();
        JsonObject responseObject = gson.fromJson(jsonString, JsonObject.class);

        return responseObject.entrySet().stream()
                .map(Map.Entry::getKey)
                .collect(toList());
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: CloneWorkFlowTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void getProjectByNonExistingCloneCodeViaHttp() throws Exception {
    AsyncHttpClient httpclient = new DefaultAsyncHttpClient(
            new DefaultAsyncHttpClientConfig.Builder()
                    .setUserAgent(null)
                    .setKeepAlive(true)
                    .build()
    );

    Future<Response> f = httpclient.prepareGet("http://localhost:" + properties.getHttpPort() + "/" + 123 + "/clone").execute();
    Response response = f.get();
    assertEquals(500, response.getStatusCode());
    String responseBody = response.getResponseBody();
    assertEquals("Requested QR not found.", responseBody);
    httpclient.close();
}
 
Example 5
Source File: AsyncHttpClientService.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse executeRequest(String url) throws Exception {
    RequestBuilder requestBuilder = new RequestBuilder()
            .setUrl(url)
            .setHeader(HEADER_KEY_CLIENT_TYPE, getClientType().getValue());

    Response response = httpClient.executeRequest(requestBuilder)
            .toCompletableFuture()
            .get(TIMEOUT_AMOUNT_IN_SECONDS, TimeUnit.SECONDS);

    return new ClientResponse(response.getResponseBody(), response.getStatusCode());
}
 
Example 6
Source File: SlaveMetaSupplier.java    From qmq with Apache License 2.0 5 votes vote down vote up
private String getServerAddress(String groupName) {
    try {
        Response response = ASYNC_HTTP_CLIENT.prepareGet(serverMetaAcquiredUrl).addQueryParam("groupName", groupName).execute().get();
        if (response.getStatusCode() == HttpResponseStatus.OK.code()) {
            String address = response.getResponseBody();
            if (!Strings.isNullOrEmpty(address)) {
                return address;
            }
        }
    } catch (Exception e) {
        LOG.error("Get server address error.", e);
    }
    return null;
}
 
Example 7
Source File: BAOSBasedCompletionHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public Response onCompleted(final Response response) {
  if (requestFailed) {
    throw new RuntimeException(response.getResponseBody());
  }
  return response;
}
 
Example 8
Source File: BufferBasedCompletionHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public Response onCompleted(Response response) {
  if (requestFailed) {
    logger.error("Error response received {} {}", response.getStatusCode(), response.getResponseBody());
    throw new RuntimeException(response.getResponseBody());
  }
  return response;
}
 
Example 9
Source File: DRPCQueryResultPubscriber.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
private void handleResponse(String id, Response response) {
    if (response == null || response.getStatusCode() != OK_200) {
        log.error("Handling error for id {} with response {}", id, response);
        responses.offer(new PubSubMessage(id, DRPCError.CANNOT_REACH_DRPC.asJSONClip()));
        return;
    }
    log.info("Received for id {}: {} {}", response.getStatusCode(), id, response.getStatusText());
    String body = response.getResponseBody();
    PubSubMessage message = PubSubMessage.fromJSON(body);
    log.debug("Received for id {}:\n{}", message.getId(), message.getContent());
    responses.offer(message);
}
 
Example 10
Source File: IndicesAdminClient.java    From flummi with Apache License 2.0 5 votes vote down vote up
public JsonObject getIndexMapping(String indexName) {
    try {
        Response response = httpClient.prepareGet("/" + indexName + "/_mapping")
                .addHeader(CONTENT_TYPE, APPL_JSON)
                .execute().get();
        if (response.getStatusCode() != 200) {
            throw RequestBuilderUtil.toHttpServerErrorException(response);
        }
        String jsonString = null;
        jsonString = response.getResponseBody();
        return gson.fromJson(jsonString, JsonObject.class);
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: AbstractRestClient.java    From async-gamequery-lib with MIT License 5 votes vote down vote up
/**
 * <p>Function that is responsible for parsing the internal response of the message (e.g. JSON or XML)</p>
 *
 * @param response
 *
 * @return Returns instance of {@link AbstractWebApiResponse}
 */
private Res applyContentTypeProcessor(Res response) {
    if (response != null && response.getMessage() != null) {
        Response msg = response.getMessage();
        String body = msg.getResponseBody();
        ContentTypeProcessor processor = contentProcessorMap.get(parseContentType(msg.getContentType()));
        if (log.isDebugEnabled() && processor == null)
            log.debug("No Content-Type processor found for {}. Please register a ContentTypeProcessor using registerContentProcessor()", parseContentType(msg.getContentType()));
        response.setProcessedContent((processor != null) ? processor.apply(body) : body);
    }
    return response;
}
 
Example 12
Source File: AhcIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncHttpClient() throws Exception {

    try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
        Future<Response> f = client.prepareGet(HTTP_URL).execute();
        Response res = f.get();
        Assert.assertEquals(200, res.getStatusCode());
        final String body = res.getResponseBody();
        Assert.assertTrue("Got body " + body, body.contains("Welcome to WildFly"));
    }
}
 
Example 13
Source File: SlaManager.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
private boolean coordinatorAllows(
    IScheduledTask task,
    String taskKey,
    ICoordinatorSlaPolicy slaPolicy,
    Map<String, String> params)
    throws InterruptedException, ExecutionException, TException {

  LOG.info("Checking coordinator: {} for task: {}", slaPolicy.getCoordinatorUrl(), taskKey);

  String taskConfig = new TSerializer(new TSimpleJSONProtocol.Factory())
      .toString(task.newBuilder());
  JsonObject jsonBody = new JsonObject();
  jsonBody.add("taskConfig", new JsonParser().parse(taskConfig));
  jsonBody.addProperty(TASK_PARAM, taskKey);
  params.forEach(jsonBody::addProperty);

  Response response = httpClient.preparePost(slaPolicy.getCoordinatorUrl())
      .setQueryParams(ImmutableList.of(new Param(TASK_PARAM, taskKey)))
      .setBody(new Gson().toJson(jsonBody))
      .execute()
      .get();

  if (response.getStatusCode() != HttpConstants.ResponseStatusCodes.OK_200) {
    LOG.error("Request failed to coordinator: {} for task: {}. Response: {}",
        slaPolicy.getCoordinatorUrl(),
        taskKey,
        response.getStatusCode());
    incrementErrorCount(USER_ERRORS_STAT_NAME, taskKey);
    return false;
  }

  successCounter.incrementAndGet();
  String json = response.getResponseBody();
  LOG.info("Got response: {} from {} for task: {}",
      json,
      slaPolicy.getCoordinatorUrl(),
      taskKey);

  Map<String, Boolean> result = new Gson().fromJson(
      json,
      new TypeReference<Map<String, Boolean>>() { }.getType());

  return result.get(slaPolicy.isSetStatusKey() ? slaPolicy.getStatusKey() : "drain");
}
 
Example 14
Source File: ZendeskResponseException.java    From zendesk-java-client with Apache License 2.0 4 votes vote down vote up
public ZendeskResponseException(Response resp) throws IOException {
    this(resp.getStatusCode(), resp.getStatusText(), resp.getResponseBody());
}