Java Code Examples for kong.unirest.HttpResponse#getBody()

The following examples show how to use kong.unirest.HttpResponse#getBody() . 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: ClientAuthenticator.java    From minecraft-world-downloader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Make the authentication request to the Mojang session server. We need to do this as the one sent by the
 * real client will have had our 'fake' public key instead of the server's real one, and as such the server will
 * not accept the connection.
 * @param hash hash based on the server information.
 */
public void makeRequest(String hash) throws UnirestException {
    AuthDetails details = profiles.getAuthDetails();

    Map<String, String> body = new HashMap<>();
    body.put("accessToken", details.getAccessToken());
    body.put("selectedProfile", details.getUuid());
    body.put("serverId", hash);


    HttpResponse<String> str = Unirest.post(AUTH_URL)
        .header("Content-Type", "application/json")
        .body(new Gson().toJson(body))
        .asString();

    if (str.getStatus() != STATUS_SUCCESS) {
        throw new RuntimeException("Client not authenticated! " + str.getBody());
    } else {
        System.out.println("Successfully authenticated user with Mojang session server.");
    }
}
 
Example 2
Source File: GemMetaAnalyzer.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MetaModel analyze(final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final MetaModel meta = new MetaModel(component);
    if (component.getPurl() != null) {
        final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
        try {
            final HttpResponse<JsonNode> response = ui.get(url)
                    .header("accept", "application/json")
                    .asJson();
            if (response.getStatus() == 200) {
                if (response.getBody() != null && response.getBody().getObject() != null) {
                    final String latest = response.getBody().getObject().getString("version");
                    meta.setLatestVersion(latest);
                }
            } else {
                handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
            }
        } catch (UnirestException e) {
            handleRequestException(LOGGER, e);
        }
    }
    return meta;
}
 
Example 3
Source File: NugetMetaAnalyzer.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
private boolean performVersionCheck(final MetaModel meta, final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final String url = String.format(baseUrl + VERSION_QUERY_URL, component.getPurl().getName().toLowerCase());
    try {
        final HttpResponse<JsonNode> response = ui.get(url)
                .header("accept", "application/json")
                .asJson();
        if (response.getStatus() == 200) {
            if (response.getBody() != null && response.getBody().getObject() != null) {
                final JSONArray versions = response.getBody().getObject().getJSONArray("versions");
                final String latest = versions.getString(versions.length()-1); // get the last version in the array
                meta.setLatestVersion(latest);
            }
            return true;
        } else {
            handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
        }
    } catch (UnirestException e) {
        handleRequestException(LOGGER, e);
    }
    return false;
}
 
Example 4
Source File: FortifySscClient.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public String generateOneTimeUploadToken(final String username, final String password) {
    LOGGER.debug("Generating one-time upload token");
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final JSONObject payload = new JSONObject().put("fileTokenType", "UPLOAD");
    final HttpRequestWithBody request = ui.post(baseURL + "/api/v1/fileTokens");
    final HttpResponse<JsonNode> response = request
            .header("Content-Type", "application/json")
            .basicAuth(username, password)
            .body(payload)
            .asJson();
    if (response.getStatus() == 201) {
        if (response.getBody() != null) {
            final JSONObject root = response.getBody().getObject();
            LOGGER.debug("One-time upload token retrieved");
            return root.getJSONObject("data").getString("token");
        }
    } else {
        LOGGER.warn("Fortify SSC Client did not receive expected response while attempting to generate a "
                + "one-time-use fileupload token. HTTP response code: "
                + response.getStatus() + " - " + response.getStatusText());
        uploader.handleUnexpectedHttpResponse(LOGGER, request.getUrl(), response.getStatus(), response.getStatusText());
    }
    return null;
}
 
Example 5
Source File: ServerAuthenticator.java    From minecraft-world-downloader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Verify the user that is connecting to us is actually the user who we just authenticated with Mojang, otherwise
 * we could be giving a malicious user access to our account on the server we are proxying. The user would
 * also have to supply a username matching ours so it should never be accidentally attempted.
 * @param hash hash based on the server information.
 */
public void makeRequest(String hash) throws UnirestException {
    HttpResponse<JsonNode> str = Unirest.get(AUTH_URL)
        .queryString("username", username)
        .queryString("serverId", hash)
        .asJson();

    if (str.getStatus() != 200) {
        System.out.println("WARNING: Connection attempt by using pretending to be you! Closing connection.");
        throw new RuntimeException("Server could not authenticate client! " + str.getBody());
    } else {
        System.out.println("User identity confirmed with Mojang.");
    }
}
 
Example 6
Source File: UnirestService.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse executeRequest(String url) {
    HttpResponse<String> response = Unirest.get(url)
            .header(HEADER_KEY_CLIENT_TYPE, getClientType().getValue())
            .asString();

    return new ClientResponse(response.getBody(), response.getStatus());
}
 
Example 7
Source File: NpmMetaAnalyzer.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MetaModel analyze(final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final MetaModel meta = new MetaModel(component);
    if (component.getPurl() != null) {

        final String packageName;
        if (component.getPurl().getNamespace() != null) {
            packageName = component.getPurl().getNamespace().replace("@", "%40") + "%2F" + component.getPurl().getName();
        } else {
            packageName = component.getPurl().getName();
        }

        final String url = String.format(baseUrl + API_URL, packageName);
        try {
            final HttpResponse<JsonNode> response = ui.get(url)
                    .header("accept", "application/json")
                    .asJson();
            if (response.getStatus() == 200) {
                if (response.getBody() != null && response.getBody().getObject() != null) {
                    final String latest = response.getBody().getObject().getString("latest");
                    meta.setLatestVersion(latest);
                }
            } else {
                handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
            }
        } catch (UnirestException e) {
            handleRequestException(LOGGER, e);
        }
    }
    return meta;
}
 
Example 8
Source File: KennaSecurityUploader.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Override
public void upload(final InputStream payload) {
    LOGGER.debug("Uploading payload to KennaSecurity");
    final ConfigProperty tokenProperty = qm.getConfigProperty(KENNA_TOKEN.getGroupName(), KENNA_TOKEN.getPropertyName());
    try {
        final UnirestInstance ui = UnirestFactory.getUnirestInstance();
        final String token = DataEncryption.decryptAsString(tokenProperty.getPropertyValue());
        final HttpRequestWithBody request = ui.post(String.format(CONNECTOR_UPLOAD_URL, connectorId));
        final HttpResponse<JsonNode> response = request
                .header("X-Risk-Token", token)
                .header("accept", "application/json")
                .field("file", payload, ContentType.APPLICATION_JSON, "findings.json")
                .field("run", "true")
                .asJson();
        if (response.getStatus() == 200 && response.getBody() != null) {
            final JSONObject root = response.getBody().getObject();
            if (root.getString("success").equals("true")) {
                LOGGER.debug("Successfully uploaded KDI");
                return;
            }
            LOGGER.warn("An unexpected response was received uploading findings to Kenna Security");
        } else {
            LOGGER.warn("Kenna uploader did not receive expected response while attempting to upload "
                    + "Dependency-Track findings. HTTP response code: "
                    + response.getStatus() + " - " + response.getStatusText());
            handleUnexpectedHttpResponse(LOGGER, request.getUrl(), response.getStatus(), response.getStatusText());
        }
    } catch (Exception e) {
        LOGGER.error("An error occurred attempting to upload findings to Kenna Security", e);
    }
}