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

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

Introduction

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

Prototype

public StringRequestEntity(String paramString1, String paramString2, String paramString3)
  throws UnsupportedEncodingException

Source Link

Usage

From source file:org.apache.jackrabbit.webdav.server.BindTest.java

public void testBindOverwrite() throws Exception {
    String testcol = this.root + "testSimpleBind/";
    String subcol1 = testcol + "bindtest1/";
    String testres1 = subcol1 + "res1";
    String subcol2 = testcol + "bindtest2/";
    String testres2 = subcol2 + "res2";
    int status;//from  w  w w. j av  a  2  s  . c  om
    try {
        MkColMethod mkcol = new MkColMethod(testcol);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create new resource R with path bindtest1/res1
        PutMethod put = new PutMethod(testres1);
        put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        //create new resource R' with path bindtest2/res2
        put = new PutMethod(testres2);
        put.setRequestEntity(new StringRequestEntity("bar", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        //try to create new binding of R with path bindtest2/res2 and Overwrite:F
        DavMethodBase bind = new BindMethod(subcol2, new BindInfo(testres1, "res2"));
        bind.addRequestHeader(new Header("Overwrite", "F"));
        status = this.client.executeMethod(bind);
        assertEquals(412, status);

        //verify that bindtest2/res2 still points to R'
        GetMethod get = new GetMethod(testres2);
        status = this.client.executeMethod(get);
        assertEquals(200, status);
        assertEquals("bar", get.getResponseBodyAsString());

        //create new binding of R with path bindtest2/res2
        bind = new BindMethod(subcol2, new BindInfo(testres1, "res2"));
        status = this.client.executeMethod(bind);
        assertTrue("status: " + status, status == 200 || status == 204);

        //verify that bindtest2/res2 now points to R
        get = new GetMethod(testres2);
        status = this.client.executeMethod(get);
        assertEquals(200, status);
        assertEquals("foo", get.getResponseBodyAsString());

        //verify that the initial binding is still there
        HeadMethod head = new HeadMethod(testres1);
        status = this.client.executeMethod(head);
        assertEquals(200, status);
    } finally {
        DeleteMethod delete = new DeleteMethod(testcol);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204);
    }
}

From source file:org.apache.jackrabbit.webdav.server.BindTest.java

public void testRebindOverwrite() throws Exception {
    String testcol = this.root + "testSimpleBind/";
    String subcol1 = testcol + "bindtest1/";
    String testres1 = subcol1 + "res1";
    String subcol2 = testcol + "bindtest2/";
    String testres2 = subcol2 + "res2";
    int status;//  www .  j  av a2  s. c o m
    try {
        MkColMethod mkcol = new MkColMethod(testcol);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create new resource R with path testSimpleBind/bindtest1/res1
        PutMethod put = new PutMethod(testres1);
        put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        // enabling version control always makes the resource referenceable
        VersionControlMethod versioncontrol = new VersionControlMethod(testres1);
        status = this.client.executeMethod(versioncontrol);
        assertTrue("status: " + status, status == 200 || status == 201);

        //create new resource R' with path testSimpleBind/bindtest2/res2
        put = new PutMethod(testres2);
        put.setRequestEntity(new StringRequestEntity("bar", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        //try rebind R with path testSimpleBind/bindtest2/res2 and Overwrite:F
        RebindMethod rebind = new RebindMethod(subcol2, new RebindInfo(testres1, "res2"));
        rebind.addRequestHeader(new Header("Overwrite", "F"));
        status = this.client.executeMethod(rebind);
        assertEquals(412, status);

        //verify that testSimpleBind/bindtest2/res2 still points to R'
        GetMethod get = new GetMethod(testres2);
        status = this.client.executeMethod(get);
        assertEquals(200, status);
        assertEquals("bar", get.getResponseBodyAsString());

        //rebind R with path testSimpleBind/bindtest2/res2
        rebind = new RebindMethod(subcol2, new RebindInfo(testres1, "res2"));
        status = this.client.executeMethod(rebind);
        assertTrue("status: " + status, status == 200 || status == 204);

        //verify that testSimpleBind/bindtest2/res2 now points to R
        get = new GetMethod(testres2);
        status = this.client.executeMethod(get);
        assertEquals(200, status);
        assertEquals("foo", get.getResponseBodyAsString());

        //verify that the initial binding is gone
        HeadMethod head = new HeadMethod(testres1);
        status = this.client.executeMethod(head);
        assertEquals(404, status);
    } finally {
        DeleteMethod delete = new DeleteMethod(testcol);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204);
    }
}

From source file:org.apache.jackrabbit.webdav.server.BindTest.java

public void testParentSet() throws Exception {
    String testcol = this.root + "testParentSet/";
    String subcol1 = testcol + "bindtest1/";
    String testres1 = subcol1 + "res1";
    String subcol2 = testcol + "bindtest2/";
    String testres2 = subcol2 + "res2";
    int status;//  w  w  w.j a v a  2s. c o m
    try {
        MkColMethod mkcol = new MkColMethod(testcol);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create new resource R with path testSimpleBind/bindtest1/res1
        PutMethod put = new PutMethod(testres1);
        put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        //create new binding of R with path testSimpleBind/bindtest2/res2
        DavMethodBase bind = new BindMethod(subcol2, new BindInfo(testres1, "res2"));
        status = this.client.executeMethod(bind);
        assertEquals(201, status);
        //check if both bindings report the same DAV:resource-id
        assertEquals(this.getResourceId(testres1), this.getResourceId(testres2));

        //verify values of parent-set properties
        List hrefs1 = new ArrayList();
        List segments1 = new ArrayList();
        List hrefs2 = new ArrayList();
        List segments2 = new ArrayList();
        Object ps1 = this.getParentSet(testres1).getValue();
        Object ps2 = this.getParentSet(testres2).getValue();
        assertTrue(ps1 instanceof List);
        assertTrue(ps2 instanceof List);
        List plist1 = (List) ps1;
        List plist2 = (List) ps2;
        assertEquals(2, plist1.size());
        assertEquals(2, plist2.size());
        for (int k = 0; k < 2; k++) {
            Object pObj1 = plist1.get(k);
            Object pObj2 = plist2.get(k);
            assertTrue(pObj1 instanceof Element);
            assertTrue(pObj2 instanceof Element);
            ParentElement p1 = ParentElement.createFromXml((Element) pObj1);
            ParentElement p2 = ParentElement.createFromXml((Element) pObj2);
            hrefs1.add(p1.getHref());
            hrefs2.add(p2.getHref());
            segments1.add(p1.getSegment());
            segments2.add(p2.getSegment());
        }
        Collections.sort(hrefs1);
        Collections.sort(hrefs2);
        Collections.sort(segments1);
        Collections.sort(segments2);
        assertEquals(hrefs1, hrefs2);
        assertEquals(segments1, segments2);
    } finally {
        DeleteMethod delete = new DeleteMethod(testcol);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204);
    }
}

From source file:org.apache.jackrabbit.webdav.server.BindTest.java

public void testBindCollections() throws Exception {
    String testcol = this.root + "testBindCollections/";
    String a1 = testcol + "a1/";
    String b1 = a1 + "b1/";
    String c1 = b1 + "c1/";
    String x1 = c1 + "x1";
    String a2 = testcol + "a2/";
    String b2 = a2 + "b2/";
    String c2 = b2 + "c2/";
    String x2 = c2 + "x2";
    int status;/*from  ww w .ja  v  a 2 s  . c  o  m*/
    try {
        MkColMethod mkcol = new MkColMethod(testcol);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(a1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(a2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create collection resource C
        mkcol = new MkColMethod(b1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(c1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create plain resource R
        PutMethod put = new PutMethod(x1);
        put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        //create new binding of C with path a2/b2
        DavMethodBase bind = new BindMethod(a2, new BindInfo(b1, "b2"));
        status = this.client.executeMethod(bind);
        assertEquals(201, status);
        //check if both bindings report the same DAV:resource-id
        assertEquals(this.getResourceId(b1), this.getResourceId(b2));

        mkcol = new MkColMethod(c2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create new binding of R with path a2/b2/c2/r2
        bind = new BindMethod(c2, new BindInfo(x1, "x2"));
        status = this.client.executeMethod(bind);
        assertEquals(201, status);
        //check if both bindings report the same DAV:resource-id
        assertEquals(this.getResourceId(x1), this.getResourceId(x2));

        //verify different path alternatives
        URI rid = this.getResourceId(x1);
        assertEquals(rid, this.getResourceId(x2));
        assertEquals(rid, this.getResourceId(testcol + "a2/b2/c1/x1"));
        assertEquals(rid, this.getResourceId(testcol + "a1/b1/c2/x2"));
        Object ps = this.getParentSet(x1).getValue();
        assertTrue(ps instanceof List);
        assertEquals(2, ((List) ps).size());
        ps = this.getParentSet(x2).getValue();
        assertTrue(ps instanceof List);
        assertEquals(2, ((List) ps).size());
    } finally {
        DeleteMethod delete = new DeleteMethod(testcol);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204);
    }
}

From source file:org.apache.jackrabbit.webdav.server.BindTest.java

public void testUnbind() throws Exception {
    String testcol = this.root + "testUnbind/";
    String subcol1 = testcol + "bindtest1/";
    String testres1 = subcol1 + "res1";
    String subcol2 = testcol + "bindtest2/";
    String testres2 = subcol2 + "res2";
    int status;/*from   w w  w  .j a va  2s. c o  m*/
    try {
        MkColMethod mkcol = new MkColMethod(testcol);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create new resource R with path testSimpleBind/bindtest1/res1
        PutMethod put = new PutMethod(testres1);
        put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        //create new binding of R with path testSimpleBind/bindtest2/res2
        DavMethodBase bind = new BindMethod(subcol2, new BindInfo(testres1, "res2"));
        status = this.client.executeMethod(bind);
        assertEquals(201, status);
        //check if both bindings report the same DAV:resource-id
        assertEquals(this.getResourceId(testres1), this.getResourceId(testres2));

        //remove new path
        UnbindMethod unbind = new UnbindMethod(subcol2, new UnbindInfo("res2"));
        status = this.client.executeMethod(unbind);
        assertTrue("status: " + status, status == 200 || status == 204);

        //verify that the new binding is gone
        HeadMethod head = new HeadMethod(testres2);
        status = this.client.executeMethod(head);
        assertEquals(404, status);

        //verify that the initial binding is still there
        head = new HeadMethod(testres1);
        status = this.client.executeMethod(head);
        assertEquals(200, status);
    } finally {
        DeleteMethod delete = new DeleteMethod(testcol);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204);
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

private String sendPostData(PostMethod post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();
    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        String contentEncoding = getContentEncoding();
        if (isNullOrEmptyTrimmed(contentEncoding)) {
            contentEncoding = null;/* www  .java2s  .c o m*/
        }

        final boolean browserCompatible = getDoBrowserCompatibleMultipart();
        // We don't know how many entries will be skipped
        List<PartBase> partlist = new ArrayList<>();
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringPart part = new StringPart(arg.getName(), arg.getValue(), contentEncoding);
            if (browserCompatible) {
                part.setTransferEncoding(null);
                part.setContentType(null);
            }
            partlist.add(part);
        }

        // Add any files
        for (HTTPFileArg file : files) {
            File inputFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            // We do not know the char set of the file to be uploaded, so we set it to null
            ViewableFilePart filePart = new ViewableFilePart(file.getParamName(), inputFile, file.getMimeType(),
                    null);
            filePart.setCharSet(null); // We do not know what the char set of the file is
            partlist.add(filePart);
        }

        // Set the multipart for the post
        int partNo = partlist.size();
        Part[] parts = partlist.toArray(new Part[partNo]);
        MultipartRequestEntity multiPart = new MultipartRequestEntity(parts, post.getParams());
        post.setRequestEntity(multiPart);

        // Set the content type
        String multiPartContentType = multiPart.getContentType();
        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, multiPartContentType);

        // If the Multipart is repeatable, we can send it first to
        // our own stream, without the actual file content, so we can return it
        if (multiPart.isRepeatable()) {
            // For all the file multiparts, we must tell it to not include
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(true); // .sendMultipartWithoutFileContent(bos);
                }
            }
            // Write the request to our own stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            multiPart.writeRequest(bos);
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();

            // For all the file multiparts, we must revert the hiding of
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(false);
                }
            }
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }
    } else {
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileRequestEntity fileRequestEntity = new FileRequestEntity(new File(file.getPath()), null);
            post.setRequestEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            String contentEncoding = getContentEncoding();
            boolean haveContentEncoding = false;
            if (isNullOrEmptyTrimmed(contentEncoding)) {
                contentEncoding = null;
            } else {
                post.getParams().setContentCharset(contentEncoding);
                haveContentEncoding = true;
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    String value;
                    if (haveContentEncoding) {
                        value = arg.getEncodedValue(contentEncoding);
                    } else {
                        value = arg.getEncodedValue();
                    }
                    postBody.append(value);
                }
                StringRequestEntity requestEntity = new StringRequestEntity(postBody.toString(),
                        post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(), contentEncoding);
                post.setRequestEntity(requestEntity);
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        String urlContentEncoding = contentEncoding;
                        if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                            // Use the default encoding for urls
                            urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                        }
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    post.addParameter(parameterName, parameterValue);
                }

                /*
                //                    // Alternative implementation, to make sure that HTTPSampler and HTTPSampler2
                //                    // sends the same post body.
                //
                //                    // Only include the content char set in the content-type header if it is not
                //                    // an APPLICATION_X_WWW_FORM_URLENCODED content type
                //                    String contentCharSet = null;
                //                    if(!post.getRequestHeader(HEADER_CONTENT_TYPE).getValue().equals(APPLICATION_X_WWW_FORM_URLENCODED)) {
                //                        contentCharSet = post.getRequestCharSet();
                //                    }
                //                    StringRequestEntity requestEntity = new StringRequestEntity(getQueryString(contentEncoding), post.getRequestHeader(HEADER_CONTENT_TYPE).getValue(), contentCharSet);
                //                    post.setRequestEntity(requestEntity);
                */
            }

            // If the request entity is repeatable, we can send it first to
            // our own stream, so we can return it
            if (post.getRequestEntity().isRepeatable()) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                post.getRequestEntity().writeRequest(bos);
                bos.flush();
                // We get the posted bytes using the encoding used to create it
                postedBody.append(new String(bos.toByteArray(), post.getRequestCharSet()));
                bos.close();
            } else {
                postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
            }
        }
    }
    // Set the content length
    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH,
            Long.toString(post.getRequestEntity().getContentLength()));

    return postedBody.toString();
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Set up the PUT/PATCH/DELETE data// w  w w. j  a v  a2  s . c  o m
 */
private String sendEntityData(EntityEnclosingMethod put) throws IOException {
    // Buffer to hold the put body, except file content
    StringBuilder putBody = new StringBuilder(1000);
    boolean hasPutBody = false;

    // Check if the header manager had a content type header
    // This allows the user to specify his own content-type for a POST request
    Header contentTypeHeader = put.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE);
    boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
            && contentTypeHeader.getValue().length() > 0;
    HTTPFileArg[] files = getHTTPFiles();

    // If there are no arguments, we can send a file as the body of the request

    if (!hasArguments() && getSendFileAsPostBody()) {
        hasPutBody = true;

        // If getSendFileAsPostBody returned true, it's sure that file is not null
        File reservedFile = FileServer.getFileServer().getResolvedFile(files[0].getPath());
        FileRequestEntity fileRequestEntity = new FileRequestEntity(reservedFile, null);
        put.setRequestEntity(fileRequestEntity);
    }
    // If none of the arguments have a name specified, we
    // just send all the values as the put body
    else if (getSendParameterValuesAsPostBody()) {
        hasPutBody = true;

        // If a content encoding is specified, we set it as http parameter, so that
        // the post body will be encoded in the specified content encoding
        String contentEncoding = getContentEncoding();
        boolean haveContentEncoding = false;
        if (isNullOrEmptyTrimmed(contentEncoding)) {
            contentEncoding = null;
        } else {
            put.getParams().setContentCharset(contentEncoding);
            haveContentEncoding = true;
        }

        // Just append all the parameter values, and use that as the post body
        StringBuilder putBodyContent = new StringBuilder();
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String value = null;
            if (haveContentEncoding) {
                value = arg.getEncodedValue(contentEncoding);
            } else {
                value = arg.getEncodedValue();
            }
            putBodyContent.append(value);
        }
        String contentTypeValue = null;
        if (hasContentTypeHeader) {
            contentTypeValue = put.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue();
        }
        StringRequestEntity requestEntity = new StringRequestEntity(putBodyContent.toString(), contentTypeValue,
                put.getRequestCharSet());
        put.setRequestEntity(requestEntity);
    }
    // Check if we have any content to send for body
    if (hasPutBody) {
        // If the request entity is repeatable, we can send it first to
        // our own stream, so we can return it
        if (put.getRequestEntity().isRepeatable()) {
            putBody.append("<actual file content, not shown here>");
        } else {
            putBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
        }
        if (!hasContentTypeHeader) {
            // Allow the mimetype of the file to control the content type
            // This is not obvious in GUI if you are not uploading any files,
            // but just sending the content of nameless parameters
            // TODO: needs a multiple file upload scenerio
            HTTPFileArg file = files.length > 0 ? files[0] : null;
            if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                put.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
            }
        }
        // Set the content length
        put.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH,
                Long.toString(put.getRequestEntity().getContentLength()));
    }
    return putBody.toString();
}

From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java

private String sendPostData(HttpMethod method) throws IOException {

    String form;//from   w w w  .  j av  a  2 s.  c  o m

    if (useAuthHeader) {
        form = OAuth.formEncode(nonOAuthParams);
    } else {
        form = OAuth.formEncode(message.getParameters());
    }

    method.addRequestHeader(HEADER_CONTENT_TYPE, OAuth.FORM_ENCODED);
    method.addRequestHeader(HEADER_CONTENT_LENGTH, form.length() + ""); //$NON-NLS-1$

    if (method instanceof PostMethod || method instanceof PutMethod) {

        StringRequestEntity requestEntity = new StringRequestEntity(form, OAuth.FORM_ENCODED, OAuth.ENCODING);

        ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
    } else {
        log.error("Logic error, method must be POST or PUT to send body"); //$NON-NLS-1$
    }

    return form;
}

From source file:org.apache.kylin.jdbc.KylinClient.java

@Override
public void connect() throws IOException {
    PostMethod post = new PostMethod(baseUrl() + "/kylin/api/user/authentication");
    addHttpHeaders(post);//from www  .j a va 2  s.c o m
    StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8");
    post.setRequestEntity(requestEntity);

    httpClient.executeMethod(post);

    if (post.getStatusCode() != 200 && post.getStatusCode() != 201) {
        throw asIOException(post);
    }
}

From source file:org.apache.kylin.jdbc.KylinClient.java

private SQLResponseStub executeKylinQuery(String sql, List<StatementParameter> params) throws IOException {
    String url = baseUrl() + "/kylin/api/query";
    String project = conn.getProject();

    QueryRequest request = null;/*from  www  .  j a  v a 2s  .  c  o  m*/
    if (null != params) {
        request = new PreparedQueryRequest();
        ((PreparedQueryRequest) request).setParams(params);
        url += "/prestate"; // means prepared statement..
    } else {
        request = new QueryRequest();
    }
    request.setSql(sql);
    request.setProject(project);

    PostMethod post = new PostMethod(url);
    addHttpHeaders(post);

    String postBody = jsonMapper.writeValueAsString(request);
    logger.debug("Post body:\n " + postBody);
    StringRequestEntity requestEntity = new StringRequestEntity(postBody, "application/json", "UTF-8");
    post.setRequestEntity(requestEntity);

    httpClient.executeMethod(post);

    if (post.getStatusCode() != 200 && post.getStatusCode() != 201) {
        throw asIOException(post);
    }

    return jsonMapper.readValue(post.getResponseBodyAsStream(), SQLResponseStub.class);
}