FHIR Client Java Example
This Java example is for Java developers to use and modify when they wish to make a VSAC FHIR API call from within their program.
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
public class FhirClient {
public static void main(String[] args) throws IOException {
String fhirServerBase = "https://cts.nlm.nih.gov/fhir/";
String username = "";
String password = "d4c9d78b-83dc-499e-ae27-947cc00fb438"; // Assign an API key to password
String valueToEncode = username + ":" + password;
String basicAuthHeader = "Basic " + Base64.getEncoder().encodeToString(valueToEncode.getBytes());
HttpClient client = HttpClientBuilder.create().build();
try {
// Request sample 1: value set
HttpGet httpGet = new HttpGet();
httpGet.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
httpGet.setURI(new URIBuilder(fhirServerBase + "ValueSet/2.16.840.1.113762.1.4.1018.98").build()); // VSAC OID example
HttpResponse response = client.execute(httpGet);
String responseString = EntityUtils.toString(response.getEntity());
System.out.println(responseString);
// Request sample 2: code system lookup
httpGet.setURI(new URIBuilder(fhirServerBase + "CodeSystem/$lookup?system=http://loinc.org&code=1963-8").build());
response = client.execute(httpGet);
responseString = EntityUtils.toString(response.getEntity());
System.out.println(responseString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Last Reviewed: September 7, 2023