Apache HttpPut Example

Apache HttpPut

Following excerpt shows how you can make PUT request using org.apache.http.client.methods.HttpPut.

Source code (HttpPutExample.java)
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example: Apache HttpPut.
 *
 * @author javaQuery
 * @date 26th January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class HttpPutExample {

    public static void main(String[] args) {
        /* Create object of CloseableHttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /* Prepare put request */
        HttpPut httpPut = new HttpPut("http://www.example.com/api/customer");
        /* Add headers to get request */
        httpPut.addHeader("Authorization", "value");

        /* Prepare StringEntity from JSON */
        StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
        /* Body of request */
        httpPut.setEntity(jsonData);
        
        /* Response handler for after request execution */
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                /* Get status code */
                int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
                System.out.println("Response code: " + httpResponseCode);
                if (httpResponseCode >= 200 && httpResponseCode < 300) {
                    /* Convert response to String */
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return null;
                    /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
                }
            }
        };

        try {
            /* Execute URL and attach after execution response handler */
            String strResponse = httpClient.execute(httpPut, responseHandler);
            /* Print the response */
            System.out.println("Response: " + strResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Related
Apache HttpGet Example
Apache HttpPost Example
Apache HttpDelete Example

Apache HttpDelete Example

Apache HttpDelete

Following excerpt shows how you can make DELETE request using org.apache.http.client.methods.HttpDelete.

Source code (HttpDeleteExample.java)
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example: Apache HttpDelete.
 *
 * @author javaQuery
 * @date 26th January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class HttpDeleteExample {

    public static void main(String[] args) {
        /* Create object of CloseableHttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /* Prepare delete request */
        HttpDelete httpDelete = new HttpDelete("http://www.example.com/api/customer");
        /* Add headers to get request */
        httpDelete.addHeader("Authorization", "value");

        /* Response handler for after request execution */
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                /* Get status code */
                int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
                System.out.println("Response code: " + httpResponseCode);
                if (httpResponseCode >= 200 && httpResponseCode < 300) {
                    /* Convert response to String */
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return null;
                    /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
                }
            }
        };

        try {
            /* Execute URL and attach after execution response handler */
            String strResponse = httpClient.execute(httpDelete, responseHandler);
            /* Print the response */
            System.out.println("Response: " + strResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Related
Apache HttpGet Example
Apache HttpPost Example

Apache HttpPost Example

Apache HttpPost

Following excerpt shows how you can make POST request using org.apache.http.client.methods.HttpPost.

Source code (HttpPostExample.java)
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example: Apache HttpPost.
 * @author javaQuery
 * @date 23rd January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class HttpPostExample {
    public static void main(String[] args) throws UnsupportedEncodingException {
        /* Create object of CloseableHttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /* Prepare POST request */
        HttpPost httpPost = new HttpPost("http://www.example.com/api/customer");
        /* Add headers to POST request */
        httpPost.addHeader("Authorization", "value");
        
        /* Prepare StringEntity from JSON */
        StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
        /* Body of request */
        httpPost.setEntity(jsonData);
        
        /* Response handler for after request execution */
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                /* Get status code */
                int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
                System.out.println("Response code: " + httpResponseCode);
                if (httpResponseCode >= 200 && httpResponseCode < 300) {
                    /* Convert response to String */
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return null;
                    /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
                }
            }
        };

        try {
            /* Execute URL and attach after execution response handler */
            String strResponse = httpClient.execute(httpPost, responseHandler);
            /* Print the response */
            System.out.println("Response: " + strResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
Related
Apache HttpGet Example
Apache HttpDelete Example
Apache HttpPut Example

Apache HttpGet Example

Apache HttpGet

Following excerpt shows how you can make GET request using org.apache.http.client.methods.HttpGet.

Source code (HttpGetExample.java)
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example: Apache HttpGet.
 * @author javaQuery
 * @date 22nd January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class HttpGetExample {

    public static void main(String[] args) {
        /* Create object of CloseableHttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /* Prepare get request */
        HttpGet httpGet = new HttpGet("http://www.example.com/api/");
        /* Add headers to get request */
        httpGet.addHeader("Authorization", "value");
        httpGet.addHeader("Content-Type", "application/json");
        
        /* Response handler for after request execution */
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                /* Get status code */
                int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
                System.out.println("Response code: " + httpResponseCode);
                if (httpResponseCode >= 200 && httpResponseCode < 300) {
                    /* Convert response to String */
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return null;
                    /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
                }
            }
        };

        try {
            /* Execute URL and attach after execution response handler */
            String strResponse = httpClient.execute(httpGet, responseHandler);
            /* Print the response */
            System.out.println("Response: " + strResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
Related
Apache HttpPost Example
Apache HttpDelete Example
Apache HttpPut Example

Download and Run Amazon DynamoDB on local system

DynamoDB + Amazon Web Services

What is Amazon DynamoDB?
Amazon DynamoDB is a fast and flexible NoSQL database service for all applications that need consistent, single-digit millisecond latency at any scale. It is a fully managed cloud database and supports both document and key-value store models.

Amazon provides application to run DynamoDB on your local system. So you don't have to pay for Amzon DynamoDB service while you are developing your application and works without internet connection.

Download

Installation
Step 1: Extract the downloaded file.

Step 2: Open DynamoDB folder location in command line and execute following command. 
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

E:\Softwares\Database\dynamodb_local_2016-01-07_1.0>java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:       false
DbPath: null
SharedDb:       true
shouldDelayTransientStatuses:   false
CorsParams:     *
Step 3: Open http://localhost:8000/shell/ in your browser. (Note: DynamoDB works well in Google Chrome and Firefox)


Port 8000
By default DynamoDB uses port 8000. If another application running on same port then it'll throw an exception.
2016-01-21 08:40:10.729:WARN:oejuc.AbstractLifeCycle:FAILED SelectChannelConnector@0.0.0.0:8000: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind
        at sun.nio.ch.Net.bind0(Native Method)
        at sun.nio.ch.Net.bind(Unknown Source)
        at sun.nio.ch.Net.bind(Unknown Source)
        at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
        at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
        at org.eclipse.jetty.server.nio.SelectChannelConnector.open(SelectChannelConnector.java:187)
        at org.eclipse.jetty.server.AbstractConnector.doStart(AbstractConnector.java:316)
        at org.eclipse.jetty.server.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:265)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
        at org.eclipse.jetty.server.Server.doStart(Server.java:293)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
        at com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer.start(DynamoDBProxyServer.java:83)
        at com.amazonaws.services.dynamodbv2.local.main.ServerRunner.main(ServerRunner.java:71)
2016-01-21 08:40:10.731:WARN:oejuc.AbstractLifeCycle:FAILED org.eclipse.jetty.server.Server@7ba18f1b: java.net.BindException: Address already in use: bi
java.net.BindException: Address already in use: bind
        at sun.nio.ch.Net.bind0(Native Method)
        at sun.nio.ch.Net.bind(Unknown Source)
        at sun.nio.ch.Net.bind(Unknown Source)
        at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
        at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
        at org.eclipse.jetty.server.nio.SelectChannelConnector.open(SelectChannelConnector.java:187)
        at org.eclipse.jetty.server.AbstractConnector.doStart(AbstractConnector.java:316)
        at org.eclipse.jetty.server.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:265)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
        at org.eclipse.jetty.server.Server.doStart(Server.java:293)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
        at com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer.start(DynamoDBProxyServer.java:83)
        at com.amazonaws.services.dynamodbv2.local.main.ServerRunner.main(ServerRunner.java:71)
Could not start server on port 8000: Address already in use: bind
To use another port for DynamoDB use -port option in command line to run DynamoDB.
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -port 8001

Command line options

  • -cors value — Enable CORS support (cross-origin resource sharing) for JavaScript. You must provide a comma-separated "allow" list of specific domains. The default setting for -cors is an asterisk (*), which allows public access.
  • -dbPath value — The directory where DynamoDB will write its database file. If you do not specify this option, the file will be written to the current directory. Note that you cannot specify both --dbPath and --inMemory at once.
  • -delayTransientStatuses — Causes DynamoDB to introduce delays for certain operations. DynamoDB can perform some tasks almost instantaneously, such as create/update/delete operations on tables and indexes; however, the actual DynamoDB service requires more time for these tasks. Setting this parameter helps DynamoDB simulate the behavior of the Amazon DynamoDB web service more closely. (Currently, this parameter introduces delays only for global secondary indexes that are in either CREATING or DELETING status.)
  • -help — Prints a usage summary and options.
  • -inMemory — DynamoDB; will run in memory, instead of using a database file. When you stop DynamoDB;, none of the data will be saved. Note that you cannot specify both --dbPath and --inMemory at once.
  • -optimizeDbBeforeStartup — Optimizes the underlying database tables before starting up DynamoDB on your computer. You must also specify -dbPath when you use this parameter.
  • -port value — The port number that DynamoDB will use to communicate with your application. If you do not specify this option, the default port is 8000.
  • -sharedDb — DynamoDB will use a single database file, instead of using separate files for each credential and region. If you specify -sharedDb, all DynamoDB clients will interact with the same set of tables regardless of their region and credential configuration.

Stop DynamoDB
To stop DynamoDB, press Ctrl+C in the command prompt window.

Date in Credential scope does not match YYYYMMDD from ISO-8601 version of date from HTTP: '20160114T083022Z' != '20160114', from '20160114T083022Z'.

I got this response message while working around AWS Version 4 Signing ProcessThere ain't much to explain. Just add 

  • x-amz-date header with date format yyyyMMdd'T'HHmmss'Z'
  • And use yyyyMMdd date format in StringToSign and Credential parameter of Authorization header.

Related
Authorization header requires 'Credential' parameter.
Authorization header requires 'Signature' parameter.
Authorization header requires 'SignedHeaders' parameter.

Authorization header requires 'SignedHeaders' parameter.

I got this response message while working around AWS Version 4 Signing Process. There ain't much to explain. Just add SignedHeaders=SignedHeaders in your Authorization header.

SignedHeaders=SignedHeaders will look like...
SignedHeaders=content-type;host;x-amz-date

Complete Authorization Header
Authorization: algorithm Credential=access key ID/credential scope, SignedHeaders=SignedHeaders, Signature=signature

TO
Authorization: AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7

Related
Authorization header requires 'Credential' parameter.
Authorization header requires 'Signature' parameter.

Reference
http://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html