Sending a POST to a RESTful Web Service in Java/WebSphere Commerce

As we navigate the complexities of e-commerce and web development, sending data to RESTful web services is a crucial task, and for Java and WebSphere Commerce users, finding the right approach can be a daunting challenge. With code snippets and expert insights, we'll delve into the world of HTTP requests and response handlers to simplify the process. From setting headers to executing requests, we'll break down the steps to make a successful POST to a RESTful web service.

Akhil Pathania · 11 September 2013 · 1 min read · 19 views
Sending a POST to a RESTful Web Service in Java/WebSphere Commerce
During one of the projects i had to make a post to a RESTful Web Service, and with IBM Info-center not coming to rescue as is the case in 50% of the times, i was able to achieve this using the following code. Thought will share with you all, in case someone is on the same boat ...
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
public class RestfulPostExample {
     public final static void main(String[] args) throws Exception {
         String parms = "Customer=001b000000BBJTw&TransactionDate=2013-09-10&LoyaltyPoints=100";
         HttpClient httpclient = new DefaultHttpClient();
         try {
             HttpPost httpRequest = new HttpPost("https://blah.blah.blah/services/rest/transaction");
             httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
            HttpEntity httpEntity = new StringEntity(parms, HTTP.UTF_8);
             httpRequest.setEntity(httpEntity);
             
             System.out.println("Executing Request: " + httpRequest.getURI());
             
             // Create a response handler
             ResponseHandler<String> responseHandler = new BasicResponseHandler();
             String responseBody = httpclient.execute(httpRequest, responseHandler);
             System.out.println("----------------------------------------");
             System.out.println(responseBody);
             System.out.println("----------------------------------------");
        } finally {
             // When HttpClient instance is no longer needed,
             // shut down the connection manager to ensure
             // immediate deallocation of all system resources
             httpclient.getConnectionManager().shutdown();
         }
     }   
 }
Share X WhatsApp
Leave a Comment

Moderated — may take a moment to appear.

You Might Also Like