Search in sources :

Example 56 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project jmeter by apache.

the class HTTPHC4Impl method sendPostData.

// TODO needs cleaning up
/**
     * 
     * @param post {@link HttpPost}
     * @return String posted body if computable
     * @throws IOException if sending the data fails due to I/O
     */
protected String sendPostData(HttpPost post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();
    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;
    // 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
        Charset charset = null;
        if (haveContentEncoding) {
            charset = Charset.forName(contentEncoding);
        } else {
            charset = MIME.DEFAULT_CHARSET;
        }
        if (log.isDebugEnabled()) {
            log.debug("Building multipart with:getDoBrowserCompatibleMultipart(): {}, with charset:{}, haveContentEncoding:{}", getDoBrowserCompatibleMultipart(), charset, haveContentEncoding);
        }
        // Write the request to our own stream
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);
        if (getDoBrowserCompatibleMultipart()) {
            multipartEntityBuilder.setLaxMode();
        } else {
            multipartEntityBuilder.setStrictMode();
        }
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset));
            FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
            multipartEntityBuilder.addPart(formPart);
        }
        // Add any files
        // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
        ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
        for (int i = 0; i < files.length; i++) {
            HTTPFileArg file = files[i];
            File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType());
            multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
        }
        HttpEntity entity = multipartEntityBuilder.build();
        post.setEntity(entity);
        if (entity.isRepeatable()) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = true;
            }
            entity.writeTo(bos);
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = false;
            }
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(bos.toString(// $NON-NLS-1$ this is the default used by HttpClient
            contentEncoding == null ? // $NON-NLS-1$ this is the default used by HttpClient
            "US-ASCII" : contentEncoding));
            bos.close();
        } else {
            // $NON-NLS-1$
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>");
        }
    //            // Set the content type TODO - needed?
    //            String multiPartContentType = multiPart.getContentType().getValue();
    //            post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType);
    } else {
        // not multipart
        // 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.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0;
        // 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.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }
            // TODO is null correct?
            FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);
            post.setEntity(fileRequestEntity);
            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // the post body will be encoded in the specified content encoding
            if (haveContentEncoding) {
                post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding);
            }
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // 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.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setHeader(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();
                    // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
                    if (haveContentEncoding) {
                        postBody.append(arg.getEncodedValue(contentEncoding));
                    } else {
                        postBody.append(arg.getEncodedValue());
                    }
                }
                // Let StringEntity perform the encoding
                StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
                post.setEntity(requestEntity);
                postedBody.append(postBody.toString());
            } else {
                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                PropertyIterator args = getArguments().iterator();
                List<NameValuePair> nvps = new ArrayList<>();
                String urlContentEncoding = contentEncoding;
                if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                    // Use the default encoding for urls
                    urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                }
                while (args.hasNext()) {
                    HTTPArgument arg = (HTTPArgument) args.next().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.
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    nvps.add(new BasicNameValuePair(parameterName, parameterValue));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding);
                post.setEntity(entity);
                if (entity.isRepeatable()) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    post.getEntity().writeTo(bos);
                    bos.flush();
                    // We get the posted bytes using the encoding used to create it
                    postedBody.append(bos.toString(contentEncoding != null ? contentEncoding : SampleResult.DEFAULT_HTTP_ENCODING));
                    bos.close();
                } else {
                    postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
                }
            }
        }
    }
    return postedBody.toString();
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) HttpEntity(org.apache.http.HttpEntity) ArrayList(java.util.ArrayList) FormBodyPart(org.apache.http.entity.mime.FormBodyPart) StringEntity(org.apache.http.entity.StringEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) FileEntity(org.apache.http.entity.FileEntity) PropertyIterator(org.apache.jmeter.testelement.property.PropertyIterator) Charset(java.nio.charset.Charset) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HTTPFileArg(org.apache.jmeter.protocol.http.util.HTTPFileArg) HTTPArgument(org.apache.jmeter.protocol.http.util.HTTPArgument) Header(org.apache.http.Header) BufferedHeader(org.apache.http.message.BufferedHeader) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File)

Example 57 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project jena by apache.

the class HttpOp method convertFormParams.

private static HttpEntity convertFormParams(Params params) {
    List<NameValuePair> nvps = new ArrayList<>();
    for (Pair p : params.pairs()) nvps.add(new BasicNameValuePair(p.getName(), p.getValue()));
    HttpEntity e = new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8);
    return e;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) Pair(org.apache.jena.sparql.engine.http.Params.Pair)

Example 58 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project wildfly by wildfly.

the class AbstractCredentialStoreTestCase method doReadCredentialPostReq.

/**
     * Makes request to {@link ReadCredentialServlet} to check read secret value from credential store. It asserts HTTP status
     * code in the response.
     */
private String doReadCredentialPostReq(String credentialStore, String alias, int expectedStatus) throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException {
    String body;
    final URI uri = new URI(url.toExternalForm() + ReadCredentialServlet.SERVLET_PATH.substring(1));
    final HttpPost post = new HttpPost(uri);
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair(ReadCredentialServlet.PARAM_CREDENTIAL_STORE, credentialStore));
    nvps.add(new BasicNameValuePair(ReadCredentialServlet.PARAM_ALIAS, alias));
    post.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
    try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
        try (final CloseableHttpResponse response = httpClient.execute(post)) {
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code in HTTP response.", expectedStatus, statusCode);
            body = EntityUtils.toString(response.getEntity());
        }
    }
    return body;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URI(java.net.URI)

Example 59 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project wildfly by wildfly.

the class CustomLoginModuleTestCase method makeCall.

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(getURL());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            EntityUtils.consume(entity);
        }
        // We should get the Login Page
        StatusLine statusLine = response.getStatusLine();
        //System.out.println("Login form get: " + statusLine);
        assertEquals(200, statusLine.getStatusCode());
        /*System.out.println("Initial set of cookies:");
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }*/
        // We should now login with the user name and password
        HttpPost httpost = new HttpPost(getURL() + "j_security_check");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", user));
        nvps.add(new BasicNameValuePair("j_password", pass));
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        response = httpclient.execute(httpost);
        entity = response.getEntity();
        if (entity != null) {
            EntityUtils.consume(entity);
        }
        statusLine = response.getStatusLine();
        // Post authentication - we have a 302
        assertEquals(302, statusLine.getStatusCode());
        Header locationHeader = response.getFirstHeader("Location");
        String location = locationHeader.getValue();
        HttpGet httpGet = new HttpGet(location);
        response = httpclient.execute(httpGet);
        entity = response.getEntity();
        if (entity != null) {
            EntityUtils.consume(entity);
        }
        /*System.out.println("Post logon cookies:");
            cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }*/
        // Either the authentication passed or failed based on the expected status code
        statusLine = response.getStatusLine();
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) StatusLine(org.apache.http.StatusLine) Header(org.apache.http.Header) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 60 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project wildfly by wildfly.

the class FormAuthenticationWebFailoverTestCase method test.

@Test
public void test(@ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException {
    URI uri1 = SecureServlet.createURI(baseURL1);
    URI uri2 = SecureServlet.createURI(baseURL2);
    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        HttpPost login = new HttpPost(baseURL1.toURI().resolve("j_security_check"));
        List<NameValuePair> pairs = new ArrayList<>(2);
        pairs.add(new BasicNameValuePair("j_username", "allowed"));
        pairs.add(new BasicNameValuePair("j_password", "password"));
        login.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
        response = client.execute(login);
        try {
            Assert.assertEquals(HttpServletResponse.SC_FOUND, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        String sessionId = null;
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNotNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
            sessionId = response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        undeploy(DEPLOYMENT_1);
        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        deploy(DEPLOYMENT_1);
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpGet(org.apache.http.client.methods.HttpGet) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URI(java.net.URI) Test(org.junit.Test)

Aggregations

UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)134 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)111 HttpPost (org.apache.http.client.methods.HttpPost)105 NameValuePair (org.apache.http.NameValuePair)100 ArrayList (java.util.ArrayList)96 HttpResponse (org.apache.http.HttpResponse)74 IOException (java.io.IOException)47 HttpEntity (org.apache.http.HttpEntity)40 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)31 ClientProtocolException (org.apache.http.client.ClientProtocolException)27 UnsupportedEncodingException (java.io.UnsupportedEncodingException)26 HttpClient (org.apache.http.client.HttpClient)20 Test (org.junit.Test)20 HttpGet (org.apache.http.client.methods.HttpGet)19 Map (java.util.Map)18 JSONObject (org.json.JSONObject)18 TestHttpClient (io.undertow.testutils.TestHttpClient)14 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 HashMap (java.util.HashMap)13 Header (org.apache.http.Header)13