Search This Blog

Showing posts with label HttpClient. Show all posts
Showing posts with label HttpClient. Show all posts

Friday, November 10, 2017

Java UniRest to call POST Http/Https Protocols

add - unirest, httpasynclient, httpcore-nio jars

// to get https post

HttpResponse response = Unirest.post ( "https://www.infovijay.com/api/call" ).header ( "content-type", "application/json" ).header ( "cache-control", "no-cache" ).body ( "{\"id\":\"12345\",\"name\":\"vijay\"}\r\n" ).asString ();

System.out.println ( response.getStatus () );
System.out.println ( response.getStatusText () );
System.out.println ( response.getHeaders () );
System.out.println ( response.getBody () );



// to file download

HttpResponse is = Unirest.get ( "https://www.infovijay.com/api/file.pdf" ).asBinary ();
byte [] buffer = new byte[is.getRawBody ().available ()];
is.getRawBody ().read ( buffer );

File targetFile = new File ( "d:/abc.pdf" );
OutputStream outStream = new FileOutputStream ( targetFile );
outStream.write ( buffer );

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 );
}

Hit Counter


View My Stats