Example usage for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity

List of usage examples for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity.

Prototype

public InputStreamRequestEntity(InputStream paramInputStream, String paramString) 

Source Link

Usage

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

protected static void handleRequestData(EntityEnclosingMethod method, Object data) {
    if (method == null) {
        throw new IllegalArgumentException("Invalid method, cannot be null");
    }//from   w w  w .  j av a 2 s .c  o  m
    if (data != null) {
        RequestEntity re = null;
        if (data.getClass().isAssignableFrom(InputStream.class)) {
            re = new InputStreamRequestEntity((InputStream) data, CONTENT_TYPE_UTF8);
        } else if (data.getClass().isAssignableFrom(byte[].class)) {
            re = new ByteArrayRequestEntity((byte[]) data, CONTENT_TYPE_UTF8);
        } else if (data.getClass().isAssignableFrom(File.class)) {
            re = new FileRequestEntity((File) data, CONTENT_TYPE_UTF8);
        } else {
            // handle as a string
            try {
                re = new StringRequestEntity(data.toString(), "text/xml", ENCODING_UTF8);
            } catch (UnsupportedEncodingException e) {
                throw new HttpIOException("Encoding data using UTF8 failed :: " + e.getMessage(), e);
            }
        }
        method.setRequestEntity(re);
    }
}

From source file:org.sipfoundry.openfire.ws.PresenceEventListenerImpl.java

private String invokePost(String userId, String message) throws Exception {
    String response = null;//from   w ww  . j a va 2 s .  co  m
    InputStream stream = null;
    String websocketAddress = System.getProperty("websocket.address");
    String websocketPort = System.getProperty("websocket.port");
    if (websocketAddress != null && websocketPort != null) {
        PostMethod method = new PostMethod(getRestServerUrl(websocketAddress, new Integer(websocketPort)));
        RequestEntity re = new InputStreamRequestEntity(new ByteArrayInputStream(message.getBytes()),
                "text/x-json");
        method.setRequestEntity(re);
        method.addRequestHeader("user_id", userId);
        try {
            HttpClient client = new HttpClient();
            client.executeMethod(method);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
            IOUtils.closeQuietly(stream);
        }
    }
    return response;
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * POST the specified classpath resource to the specified HTTP endpoint.
 * @param endpointURL The HTTP endpoint URL.
 * @param requestResource The classpath resource to be posted to the endpoint.
 * @return The HTTP method.//from  w  w  w. j  a va 2  s . c o m
 */
public HttpMethod postResourceAndGetMethod(String endpointURL, String requestResource) {
    if (_dumpMessages) {
        _logger.info("Sending a POST request to [" + endpointURL + "]");
        InputStream input = getTestKit().getResourceAsStream(requestResource);
        ByteArrayOutputStream tmp = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int l = 0;
        try {
            while ((l = input.read(data)) >= 0) {
                tmp.write(data, 0, l);
            }
            _logger.info("Request body:[" + new String(tmp.toByteArray()) + "]");
        } catch (IOException e) {
            _logger.error("Unexpected Exception while reading request resource", e);
        }
    }

    PostMethod postMethod = new PostMethod(endpointURL);
    InputStream requestStream = getTestKit().getResourceAsStream(requestResource);

    try {
        postMethod.setRequestEntity(
                new InputStreamRequestEntity(requestStream, _contentType + "; charset=utf-8"));
        execute(postMethod);
    } finally {
        try {
            requestStream.close();
        } catch (IOException e) {
            Assert.fail("Unexpected exception closing HTTP request resource stream.");
        }
    }
    return postMethod;
}

From source file:org.switchyard.test.mixins.HTTPMixIn.java

/**
 * POST the specified classpath resource to the specified HTTP endpoint.
 * @param endpointURL The HTTP endpoint URL.
 * @param requestResource The classpath resource to be posted to the endpoint.
 * @return The HTTP response payload./*from   ww w.j  a  va 2 s .c  om*/
 */
public String postResource(String endpointURL, String requestResource) {
    if (_dumpMessages) {
        _logger.info("Sending a POST request to [" + endpointURL + "]");
        InputStream input = getTestKit().getResourceAsStream(requestResource);
        ByteArrayOutputStream tmp = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int l = 0;
        try {
            while ((l = input.read(data)) >= 0) {
                tmp.write(data, 0, l);
            }
            _logger.info("Request body:[" + new String(tmp.toByteArray()) + "]");
        } catch (IOException e) {
            _logger.error("Unexpected Exception while reading request resource", e);
        }
    }

    PostMethod postMethod = new PostMethod(endpointURL);
    InputStream requestStream = getTestKit().getResourceAsStream(requestResource);

    try {
        postMethod.setRequestEntity(
                new InputStreamRequestEntity(requestStream, _contentType + "; charset=utf-8"));
        return execute(postMethod);
    } finally {
        try {
            requestStream.close();
        } catch (IOException e) {
            Assert.fail("Unexpected exception closing HTTP request resource stream.");
        } finally {
            postMethod.releaseConnection();
        }
    }
}

From source file:org.vamdc.taverna.vamdc_taverna_suite.common.UWSCaller.java

/**
 * @param filename//from  w w w .j  a  va2 s  .c o m
 * @param strURL
 * @param append
 * @return
 * @throws Exception
 */
private static String getDetails(File input, String strURL, String append) throws Exception {
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream
    // Per default, the request content needs to be buffered
    // in order to determine its length.
    // Request body buffering can be avoided when
    // content length is explicitly specified

    post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
    post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");

    post.setFollowRedirects(false);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();

    try {
        //httpclient.
        int result = httpclient.executeMethod(post);
        int statuscode = post.getStatusCode();

        if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                || (statuscode == HttpStatus.SC_SEE_OTHER)
                || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

            Header header = post.getResponseHeader("location");
            System.out.println("   :  Header  :  " + header);
            if (header != null) {
                String newuri = header.getValue();
                if ((newuri == null) || (newuri.equals("")))
                    newuri = "/";
                return newuri;
            } else {
                return null;
            }
        } else {
            System.out.println(post.getResponseBodyAsString());
        }
    } finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
    }
    return null;
}

From source file:org.xwiki.test.ui.TestUtils.java

protected PutMethod executePut(String uri, InputStream content, String mediaType, int... expectedCodes)
        throws Exception {
    PutMethod putMethod = new PutMethod(uri);
    RequestEntity entity = new InputStreamRequestEntity(content, mediaType);
    putMethod.setRequestEntity(entity);/*w ww. j  a va 2s .co m*/

    int code = this.adminHTTPClient.executeMethod(putMethod);
    if (!ArrayUtils.contains(expectedCodes, code)) {
        throw new Exception("Failed to execute put [" + uri + "] with code [" + code + "]");
    }

    return putMethod;
}

From source file:org.ybygjy.httpclient.PostXML.java

/**
 *
 * Usage:/* ww w . j a va2  s  .  com*/
 *          java PostXML http://mywebserver:80/ c:\foo.xml
 *
 *  @param args command line arguments
 *                 Argument 0 is a URL to a web server
 *                 Argument 1 is a local filename
 *
 */
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println(
                "Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostXML <url> <filename>]");
        System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar");
        System.out.println("<loglevel> - one of error, warn, info, debug, trace");
        System.out.println("<url> - the URL to post the file to");
        System.out.println("<filename> - file to post to the URL");
        System.out.println();
        System.exit(1);
    }
    // Get target URL
    String strURL = args[0];
    // Get file to be posted
    String strXMLFilename = args[1];
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly 
    // from the input stream
    // Per default, the request content needs to be buffered
    // in order to determine its length.
    // Request body buffering can be avoided when
    // content length is explicitly specified
    post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
    // Specify content type and encoding
    // If content encoding is not explicitly specified
    // ISO-8859-1 is assumed
    post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}

From source file:sos.util.SOSHttpPost.java

private void sendFile(File inputFile, String outputFile) throws Exception {

    this.log_info("sending " + inputFile.getCanonicalPath() + " ...");

    int responseCode = -1;

    try {/* w w  w.j  a va  2  s  .  com*/

        String suffix = null;
        String contentType = null;
        if (inputFile.getName().lastIndexOf('.') != -1) {

            suffix = inputFile.getName().substring(inputFile.getName().lastIndexOf('.') + 1);
            if (suffix.equals("htm") || suffix.equals("html"))
                contentType = "text/html";
            if (suffix.equals("xml"))
                contentType = "text/xml";
        }

        // encoding ermitteln
        if (contentType != null)
            if (contentType.equals("text/html") || contentType.equals("text/xml")) {

                BufferedReader br = new BufferedReader(new FileReader(inputFile));
                String buffer = "";
                String line = null;
                int c = 0;
                // die ersten 5 Zeilen nach einem encoding durchsuchen
                while ((line = br.readLine()) != null || ++c > 5)
                    buffer += line;
                Pattern p = Pattern.compile("encoding[\\s]*=[\\s]*['\"](.*?)['\"]", Pattern.CASE_INSENSITIVE);
                Matcher m = p.matcher(buffer);
                if (m.find())
                    contentType += "; charset=" + m.group(1);

                br.close();
            }

        if (contentType == null)
            contentType = "text/plain";

        PostMethod post = new PostMethod(this.targetURL);

        post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(inputFile), inputFile.length()));
        post.setRequestHeader("Content-Type", contentType);
        //post.setFollowRedirects(true);

        HttpClient httpClient = new HttpClient();

        responseCode = httpClient.executeMethod(post);

        // Response Code berprfen         
        // codes 200 - 399 gehen durch
        if (responseCode < 200 || responseCode >= 400)
            throw new HttpException(this.targetURL.toString() + " returns " + post.getStatusLine().toString());

        // response
        String writeMsg = "";
        if (outputFile != null)
            writeMsg = this.writeResponse(post.getResponseBodyAsStream(), outputFile);

        // abschlieende Meldung
        this.log_info(inputFile.getCanonicalPath() + " sent" + writeMsg);

    } catch (UnknownHostException uhx) {
        throw new Exception("UnknownHostException: " + uhx.getMessage());
    } catch (FileNotFoundException nfx) {
        throw new Exception("FileNotFoundException: " + nfx.getMessage());
    } catch (HttpException htx) {
        throw new Exception("HttpException: " + htx.getMessage());
    } catch (IOException iox) {
        throw new Exception("IOException: " + iox.getMessage());
    }
}