The code snippet uses the following maven dependencies:
org.apache.httpcomponents
httpclient
4.5.7
org.apache.httpcomponents
httpcore
4.4.11
commons-logging
commons-logging
1.2
//Code snippet to consume Product Code builder API using Java
//load required libraries
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.Date;
public class PcbRestClient {
/*************************************************************************************************************************
//This is example of a complete Java class that uses Apache HttpClient to make a POST request to a REST API
*************************************************************************************************************************/
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
//create a signature and append it to the URL to avoid cached responses from server.
Long signature = generateSignature();
//set the URI
HttpPost httpPost = new HttpPost("https://www.accessdata.fda.gov/rest/pcbapi/v1/product/name/?signature="+signature);
System.out.println(httpPost.getURI());
//add the headers
httpPost.addHeader("Authorization-User", "Insert your Authorization-User here");
httpPost.addHeader("Authorization-Key", "Insert your Authorization-Key here");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//build the payload
httpPost.setEntity(new StringEntity("payload=blood/plasma"));
//execute the post request
HttpResponse httpResponse = httpClient.execute(httpPost);
//process the response received
String responseBody = EntityUtils.toString(httpResponse.getEntity());
System.out.println(responseBody);
httpClient.close();
}
private static long generateSignature() {
Date date = new Date();
long signature = date.getTime();
return signature;
}
}