Java Code Examples for com.ning.http.client.Response#getResponseBody()

The following examples show how to use com.ning.http.client.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: QConfigHttpServerClient.java    From qconfig with MIT License 6 votes vote down vote up
protected TypedCheckResult parse(Response response) throws IOException {
    LineReader reader = new LineReader(new StringReader(response.getResponseBody(Constants.UTF_8.name())));
    Map<Meta, VersionProfile> result = new HashMap<Meta, VersionProfile>();
    String line;
    try {
        while ((line = reader.readLine()) != null) {
            append(result, line);
        }
    } catch (IOException e) {
        //ignore
    }


    if (Constants.PULL.equals(response.getHeader(Constants.UPDATE_TYPE))) {
        return new TypedCheckResult(result, TypedCheckResult.Type.PULL);
    } else {
        return new TypedCheckResult(result, TypedCheckResult.Type.UPDATE);
    }
}
 
Example 2
Source File: QConfigAdminClient.java    From qconfig with MIT License 6 votes vote down vote up
@Override
protected Snapshot<String> parse(Response response) throws Exception {
    int code = Integer.parseInt(response.getHeader(Constants.CODE));
    logger.debug("response code is {}", code);
    String message = response.getResponseBody(Constants.UTF_8.name());
    logger.debug("response message is {}", message);
    if (code == ApiResponseCode.OK_CODE) {
        JsonNode jsonNode = objectMapper.readTree(message);
        JsonNode profileNode = jsonNode.get("profile");
        JsonNode versionNode = jsonNode.get("version");
        JsonNode contentNode = jsonNode.get("content");
        JsonNode statusNode = jsonNode.get("statuscode");
        if (profileNode != null
                && versionNode != null
                && contentNode != null
                && statusNode != null) {
            return new Snapshot<String>(profileNode.asText(), versionNode.asLong(), contentNode.asText(), StatusType.codeOf(statusNode.asInt()));
        }
    }
    return null;
}
 
Example 3
Source File: JsonAsyncHttpPinotClientTransport.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Override
public BrokerResponse get(long timeout, TimeUnit unit)
    throws ExecutionException {
  try {
    LOGGER.debug("Sending query {} to {}", _query, _url);

    Response httpResponse = _response.get(timeout, unit);

    LOGGER.debug("Completed query, HTTP status is {}", httpResponse.getStatusCode());

    if (httpResponse.getStatusCode() != 200) {
      throw new PinotClientException(
          "Pinot returned HTTP status " + httpResponse.getStatusCode() + ", expected 200");
    }

    String responseBody = httpResponse.getResponseBody("UTF-8");
    return BrokerResponse.fromJson(OBJECT_READER.readTree(responseBody));
  } catch (Exception e) {
    throw new ExecutionException(e);
  }
}
 
Example 4
Source File: WrappedUserResponseParser.java    From Singularity with Apache License 2.0 6 votes vote down vote up
SingularityUserPermissionsResponse parse(Response response) throws IOException {
  if (response.getStatusCode() > 299) {
    throw WebExceptions.unauthorized(
      String.format("Got status code %d when verifying jwt", response.getStatusCode())
    );
  } else {
    String responseBody = response.getResponseBody();
    SingularityUserPermissionsResponse permissionsResponse = objectMapper.readValue(
      responseBody,
      SingularityUserPermissionsResponse.class
    );
    if (!permissionsResponse.getUser().isPresent()) {
      throw WebExceptions.unauthorized(
        String.format("No user present in response %s", permissionsResponse)
      );
    }
    if (!permissionsResponse.getUser().get().isAuthenticated()) {
      throw WebExceptions.unauthorized(
        String.format("User not authenticated (response: %s)", permissionsResponse)
      );
    }
    return permissionsResponse;
  }
}
 
Example 5
Source File: RawUserResponseParser.java    From Singularity with Apache License 2.0 6 votes vote down vote up
SingularityUserPermissionsResponse parse(Response response) throws IOException {
  if (response.getStatusCode() > 299) {
    throw WebExceptions.unauthorized(
      String.format("Got status code %d when verifying jwt", response.getStatusCode())
    );
  } else {
    String responseBody = response.getResponseBody();
    WebhookAuthUser user = objectMapper.readValue(responseBody, WebhookAuthUser.class);
    return new SingularityUserPermissionsResponse(
      Optional.of(
        new SingularityUser(
          user.getUid(),
          Optional.of(user.getUid()),
          authConfiguration
            .getDefaultEmailDomain()
            .map(d -> String.format("%s@%s", user.getUid(), d)),
          user.getGroups(),
          user.getScopes(),
          true
        )
      ),
      Optional.empty()
    );
  }
}
 
Example 6
Source File: GithubRepositoryApiImpl.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private ApiResult doFile(final String project, final String ref, final String path) {
    Optional<PrivateToken> privateToken = privateTokenService.queryToken(LoginContext.getLoginContext().getLoginUser());
    if (!privateToken.isPresent()) {
        return ResultHelper.fail(-1, "尚未设置 Github Private Token");
    }

    String fileUrl = buildFileUrl(project, path);
    Request request = client.prepareGet(fileUrl)
            .addQueryParam("ref", ref)
            .addHeader("Accept", "application/json")
            .addHeader("'content-type", "application/json")
            .addHeader("Authorization", "token " + privateToken.get().getPrivateToken())
            .build();
    try {
        Response response = client.executeRequest(request).get();
        int statusCode = response.getStatusCode();
        switch (statusCode) {
            case 200:
                String responseBody = response.getResponseBody(Charsets.UTF_8.name());
                return ResultHelper.success(JacksonSerializer.deSerialize(responseBody, GitHubFile.class));
            case 401:
                return ResultHelper.fail("拒绝访问,请检查private token");
            case 404:
                return ResultHelper.fail("文件不存在,请检查链接:" + fileUrl);
            default:
                return ResultHelper.fail("请求github失败,位置的状态码:" + statusCode);
        }
    } catch (Exception e) {
        Metrics.counter("connect_github_error").inc();
        logger.error("connect github fail", e);
        return ResultHelper.fail("连接 github 失败" + e.getMessage());
    }
}
 
Example 7
Source File: ProfilerController.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private String getAnalyzerResult(String url) {
    Request request = httpClient.preparePost(url).build();
    try {
        Response response = httpClient.executeRequest(request).get();
        if (response.getStatusCode() != 200) {
            LOGGER.warn("analyze profiler result code is {}", response.getStatusCode());
            return null;
        }
        return response.getResponseBody();
    } catch (Exception e) {
        LOGGER.error("get analyzer result.", e);
        throw new RuntimeException("get analyzer result error. " + e.getMessage());
    }
}
 
Example 8
Source File: QConfigAdminClient.java    From qconfig with MIT License 5 votes vote down vote up
private static UploadResult parseUploadResult(Response response) throws IOException {
    int code = Integer.parseInt(response.getHeader(Constants.CODE));
    logger.debug("response code is {}", code);
    String message = response.getResponseBody(Constants.UTF_8.name());
    logger.debug("response message is {}", message);
    return new UploadResult(code, message);
}
 
Example 9
Source File: AggregatorEventHandler.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public void onResult(int id, Response response) {

        try {
            // TODO: Handle status codes other than 200...
            int httpStatus = response.getStatusCode();
            log.logEndProcessingStepNonBlocking(id, httpStatus);

            // If many requests completes at the same time the following code must be executed in sequence for one thread at a time
            // Since we don't have any Actor-like mechanism to rely on (for the time being...) we simply ensure that the code block is executed by one thread at a time by an old school synchronized block
            // Since the processing in the block is very limited it will not cause a bottleneck.
            synchronized (result) {
                // Count down, aggregate answer and return if all answers (also cancel timer)...
                int noOfRes = noOfResults.incrementAndGet();

                // Perform the aggregation...
                log.logMessage("Safely adding response #" + id);
                result += response.getResponseBody() + '\n';

                if (noOfRes >= noOfCalls) {
                    onAllCompleted();
                }
            }



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
Example 10
Source File: CommonG.java    From bdt with Apache License 2.0 5 votes vote down vote up
public void setResponse(String endpoint, Response response) throws IOException {

        Integer statusCode = response.getStatusCode();
        String httpResponse = response.getResponseBody();
        List<Cookie> cookies = response.getCookies();
        this.response = new HttpResponse(statusCode, httpResponse, cookies);
    }
 
Example 11
Source File: ZendeskResponseException.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public ZendeskResponseException(Response resp) throws IOException {
    this(resp.getStatusCode(), resp.getStatusText(), resp.getResponseBody());
}
 
Example 12
Source File: JsfRenderIT.java    From glowroot with Apache License 2.0 4 votes vote down vote up
@Override
protected void doTest(int port) throws Exception {
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    Response response = asyncHttpClient
            .prepareGet("http://localhost:" + port + "/hello.xhtml").execute().get();
    int statusCode = response.getStatusCode();
    if (statusCode != 200) {
        asyncHttpClient.close();
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
    String body = response.getResponseBody();
    Matcher matcher =
            Pattern.compile("action=\"/hello.xhtml;jsessionid=([0-9A-F]+)\"").matcher(body);
    matcher.find();
    String jsessionId = matcher.group(1);
    StringBuilder sb = new StringBuilder();
    matcher = Pattern
            .compile("<input type=\"hidden\" name=\"([^\"]+)\" value=\"([^\"]+)\" />")
            .matcher(body);
    matcher.find();
    sb.append(matcher.group(1));
    sb.append("=");
    sb.append(matcher.group(2));
    matcher = Pattern
            .compile("<input type=\"submit\" name=\"([^\"]+)\" value=\"([^\"]+)\" />")
            .matcher(body);
    matcher.find();
    sb.append("&");
    sb.append(matcher.group(1));
    sb.append("=");
    sb.append(matcher.group(2));
    matcher = Pattern.compile("name=\"([^\"]+)\" id=\"[^\"]+\" value=\"([^\"]+)\"")
            .matcher(body);
    matcher.find();
    sb.append("&");
    sb.append(matcher.group(1));
    sb.append("=");
    sb.append(matcher.group(2));
    String postBody = sb.toString().replace(":", "%3A");
    response = asyncHttpClient
            // ";xyz" is added to identify the second trace
            .preparePost(
                    "http://localhost:" + port + "/hello.xhtml;xyz")
            .setHeader("Content-Type", "application/x-www-form-urlencoded")
            .addCookie(Cookie.newValidCookie("JSESSIONID", jsessionId, "localhost",
                    jsessionId, null, -1, -1, true, true))
            .setBody(postBody)
            .execute()
            .get();
    statusCode = response.getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
    // sleep a bit to make sure the "last trace" is not the first http request from above
    MILLISECONDS.sleep(200);
}