Skip to content

Instantly share code, notes, and snippets.

@kgiannis
Last active June 13, 2019 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgiannis/97b57b956eeeab9af067b2df74900c3d to your computer and use it in GitHub Desktop.
Save kgiannis/97b57b956eeeab9af067b2df74900c3d to your computer and use it in GitHub Desktop.
RPC client based on Apache Http
public String call(MultichainApiCommand requestBody) throws ClientProtocolException, IOException, AuthenticationException, URISyntaxException {
/**
MultichainApiCommand requestBody -->
is a class (MultichainApiCommand) with properties:
private String method;
private Object[] params;
private UUID id;
private String chainName;
**/
// Initiate Closable HTTP client
CloseableHttpClient client = HttpClients.createDefault();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("--> Host IP here <--")
.setPort("--> Host PORT here <--")
.build();
// Prepare for POST at specified URI
HttpPost httpPost = new HttpPost(uri);
// Set Basic Authorization for POST Request
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("--> Username <--", "--> Password <--");
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
byte[] encodedAuth = Base64.getEncoder().encode(creds.getPassword().getBytes());
String authHeader = "Basic " + new String(encodedAuth);
HttpUriRequest request = RequestBuilder.post()
.setUri(MultichainConfig.uri())
.setHeader(HttpHeaders.AUTHORIZATION, authHeader)
.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
.setEntity(new StringEntity(requestBody.toString()))
.build();
// Set POST Body as String
httpPost.setEntity(new StringEntity(requestBody.toString()));
// Execute Call
CloseableHttpResponse response = client.execute(httpPost);
// Get Response From MultiChain
HttpEntity entity = response.getEntity();
String jsonResponse = EntityUtils.toString(entity, StandardCharsets.UTF_8);
return jsonResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment