Search This Blog

Friday, November 10, 2017

Java HttpClient to call POST Http/Https Protocols

                String url = "https://www.infovijay.com/api/call";
                JSONObject json = new JSONObject ();
json.put ( "id", "123" );
json.put ( "name", "vijay" );
StringEntity params = new StringEntity ( json.toString () );

/*
* HttpClient httpClient = new DefaultHttpClient();
* HttpPost httpPost = new HttpPost(url);
* ResponseHandler responseHandler = new BasicResponseHandler();
* String responseBody = null;
* try {
* httpPost.setEntity(params);
* httpPost.setHeader("Content-type", "application/json");
* httpPost.setHeader("Cache-Control", "no-cache");
* responseBody = httpClient.execute(httpPost, responseHandler);
* } catch (IOException e) {
* throw e;
* } finally {
* httpClient.getConnectionManager().shutdown();
* }
* System.out.println ( responseBody );
*/


HttpPost post = null;
HttpClient httpClient = HttpClientBuilder.create ().build ();
HttpResponse httpResponse = null;
BufferedReader br = null;
String result = null;

try
{
StringEntity jsonParams = new StringEntity ( json.toString () );
post = new HttpPost ( url );
post.setEntity ( jsonParams );
post.setHeader ( "Content-type", "application/json" );
post.setHeader ( "Cache-Control", "no-cache" );
httpResponse = httpClient.execute ( post );

br = new BufferedReader ( new InputStreamReader ( httpResponse.getEntity ().getContent () ) );
result = br.readLine ();
}
catch ( Exception e )
{
e.printStackTrace ();
}
finally
{
try
{
httpResponse = null;
post = null;
httpClient = null;

if ( br != null )
{
br.close ();
}
}
catch ( IOException e )
{
e.printStackTrace ();
}
}
System.out.println( result );
}
Post a Comment

Hit Counter


View My Stats