Example code for calling the API from an Android App

The following code shows how to call the API in Java/Android Studio, courtesy of RikTheVeggie, author of MyBricks.


/**
 * Call Brickset's API
 * @param url_ the url to invoke, eg https://brickset.com/api/v3.asmx/checkKey
 * @param params map of key-value pairs, eg API-KEY=123, username=xyz
 * @return the body (JSON), may be parsed with gson etc
 */
public static String callBrickset(final String url_, final Map params) {

    final URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(url_);

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        urlConnection.setDoOutput(true);

        final String body = Utils.getPostDataAsString(params);  // eg, "API-KEY=123&username=xyz"
        final byte[] requestBody = body.getBytes(StandardCharsets.UTF_8);
        urlConnection.setFixedLengthStreamingMode(requestBody.length);

        try (OutputStream outputStream = urlConnection.getOutputStream()) {
            outputStream.write(requestBody);
            outputStream.flush();

            final int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                // CAPTCHA required, abort processing and handle it
            }
            else
            if (responseCode != HttpURLConnection.HTTP_OK) {
                // likely a 500 caused by an invalid request, abort processing and handle it
            }

            // Response code must be ok
            try (InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream())) {
                return Utils.convertStreamToString(inputStream);
            }
        }
    } catch (IOException e) {
        // abort processing and handle it
    }
    finally {
        if ( urlConnection != null ) {
            urlConnection.disconnect();
        }
    }
}
Return to home page »