Skip to content

Instantly share code, notes, and snippets.

@diyan
Created June 23, 2023 15:58
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 diyan/ff3bac7e64476e1e627fb52844cb2e72 to your computer and use it in GitHub Desktop.
Save diyan/ff3bac7e64476e1e627fb52844cb2e72 to your computer and use it in GitHub Desktop.

Apache HttpComponents

ArrayList<NameValuePair> formParams = new ArrayList<>();
formParams.add(new BasicNameValuePair("paramA", "valueA"));
formParams.add(new BasicNameValuePair("paramB", "valueB"));
formParams.add(new BasicNameValuePair("paramC", "valueC"));

BusinessObject businessObject = new BusinessObject();

CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(myUrl);
try {
  httpPost.setEntity(new UrlEncodedFormEntity(formParams));
  HttpResponse httpResponse = httpClient.execute(httpPost);
  int httpCode = httpResponse.getStatusLine().getStatusCode();
  if(httpCode == 200) {
    businessObject = objectMapper.readValue(
      EntityUtils.toByteArray(httpResponse.getEntity()), BusinessObject.class);
  } else {
    // Not good
  }
} catch (ClientProtocolException e) {
    // Wrap and re-throw error
}

Google HTTP Client

Map<String, String> formParams = new LinkedHashMap<>();
formParams.put("paramA", "valueA");
formParams.put("paramB", "valueB");
formParams.put("paramC", "valueC");
HttpContent formParamsEncoded = new UrlEncodedContent(formParams);
    
BusinessObject businessObject = new BusinessObject();
HttpResponse httpResponse = null;
  
try {
  httpResponse = httpTransport.createRequestFactory()
    .buildPostRequest(new GenericUrl(myUrl), formParamsEncoded)
    .setThrowExceptionOnExecuteError(false)
    .execute();
  int httpCode = httpResponse.getStatusCode();
  businessObject = objectMapper.readValue(httpResponse.parseAsString(), BusinessObject.class);
  
  if (httpCode == 200) {
    // Good
  } else {
    // Not good
  }
} catch (IOException e) {
  // Wrap and re-throw error
}
finally {
  if (httpResponse != null) {
    httpResponse.disconnect();
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment