Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Usually service integrations are via posting JSON or XML. I had a need to integrate with a service that used an HTTP form post. Wait, what? How do you do that? Springframework provides a MultiValueMap interface that is posted as form data. LinkedMultiValueMap is an implementation of the MultiValueMap interface. The MultiValueMap is backed by a LinkedHashMap as opposed to a Map. Hence, it uses add instead of put.

Let’s see it in some code…

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
// properties that identify our system, etc
map.add("username", username);
map.add("password", password);
map.add("ageToCheck", ageToCheck);
map.add("firstName", kycModel.getFirstName());
map.add("lastName", kycModel.getLastName());
map.add("address", kycModel.getAddress());
map.add("city", kycModel.getCity());
map.add("state", kycModel.getState());
map.add("zip", kycModel.getZip());
map.add("dobMonth", kycModel.getDobMonth());
map.add("dobDay", kycModel.getDobDay());
map.add("dobYear", kycModel.getDobYear());
map.add("ssnLast4", kycModel.getSsnLast4());

Response response = restTemplate.postForObject(url, map, Response.class);

From there on, the RestTemplate works as it normally does.

September 22nd, 2015

Posted In: Java, java ninja, Javaninja, Spring

Tags: , , , ,

Leave a Comment

Continuing from my Http Get Example, here is an example of an HttpClient4 String post example.

     * Performs HTTP post.
     * @param url http resource to post
     * @return string response
    protected String post(String url) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = null;
        try {
            responseBody = httpClient.execute(httpPost, responseHandler);
        } catch (IOException e) {
            log.error("IOException", e);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
        return responseBody;

December 11th, 2014

Posted In: Java

Tags: , , , , , , , ,

One Comment

WP to LinkedIn Auto Publish Powered By :