Show TOC

Posting File Using Chunked EncodingLocate this document in the navigation structure

Use

The following example shows a direct chunked encoded POST of the specified file data to the specified URI:

            import com.sap.httpclient.HttpClient;
import com.sap.httpclient.http.methods.POST;
import com.sap.httpclient.http.methods.InputStreamRequestData;
import com.sap.httpclient.http.HttpStatus;
import java.io.File;
import java.io.FileInputStream;

/**
 * This example makes a direct chunked encoded post of the 
 * specified file data to the specified uri.
 *
 */
public class SimpleExample3 {
        public static void main(String[] args) {
                try {
                        // getting the uri and file values from the arguments
                        String uri = args[0]; // format should be 
                        // http://<host>[:port]/<post path>
                        String fileName = args[1];

                        // creating the http client instance
                        HttpClient client = new HttpClient();

                        // creating the post method instance with the specified uri
                        POST httppost = new POST(uri);

                        // creating a pointer to the file
                        File file = new File(fileName);

                        // setting the request data to the method ->
                        // stream to the file
                        httppost.setRequestData(new InputStreamRequestData(
                                        new FileInputStream(file)));

                        // setting the chunked content
                        httppost.setContentChunked(true);

                        try {
                                // executing the method
                                client.executeMethod(httppost);

                                // checking the status and showing the response
                                if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                                        System.out.println(httppost.getResponseBodyAsString());
                                } else {
                                        System.out.println("Unexpected failure: "
                                                        + httppost.getStatusLine().toString());
                                }
                        } finally {
                                httppost.releaseConnection();
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("USSAGE : java SimpleExample3"
                                        + " <uri> <data filename>");
                }
        }
}