Example usage for org.apache.http.entity ContentType APPLICATION_FORM_URLENCODED

List of usage examples for org.apache.http.entity ContentType APPLICATION_FORM_URLENCODED

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType APPLICATION_FORM_URLENCODED.

Prototype

ContentType APPLICATION_FORM_URLENCODED

To view the source code for org.apache.http.entity ContentType APPLICATION_FORM_URLENCODED.

Click Source Link

Usage

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private HttpPost createPostRequest(URI uri, String postBody, String contentTypes, ServerInfo serverInfo) {
    HttpPost httpPost = new HttpPost(uri);
    ContentType contentType = ContentType.create(contentTypes);
    if (contentType == null)
        throw new RuntimeException("Couldn't create content types for " + contentTypes);

    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType())) {
        String tokenToUse = null;
        if (serverInfo.encryptedToken != null) {
            try {
                tokenToUse = Crypto.doDecrypt(serverInfo.encryptedToken);
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }/*from   ww  w.  j a v a2 s  .  co  m*/
        }
        List<NameValuePair> params = parseQueryStringAndAddToken(postBody, tokenToUse);
        postBody = URLEncodedUtils.format(params, "UTF-8");
    }

    StringEntity entity = new StringEntity(postBody, contentType);
    httpPost.setEntity(entity);

    return httpPost;
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private HttpRequestBase buildHttpRequest(URI hostURI, HttpDispatcherProperties httpDispatcherProperties,
        ConnectorMessage connectorMessage, File tempFile, ContentType contentType, Charset charset)
        throws Exception {
    String method = httpDispatcherProperties.getMethod();
    boolean isMultipart = httpDispatcherProperties.isMultipart();
    Map<String, List<String>> headers = httpDispatcherProperties.getHeaders();
    Map<String, List<String>> parameters = httpDispatcherProperties.getParameters();

    Object content = null;// w  ww. j a va 2 s .  c om
    if (httpDispatcherProperties.isDataTypeBinary()) {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage, null, true);
    } else {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage);

        // If text mode is used and a specific charset isn't already defined, use the one from the connector properties
        if (contentType.getCharset() == null) {
            contentType = HttpMessageConverter.setCharset(contentType, charset);
        }
    }

    // populate the query parameters
    List<NameValuePair> queryParameters = new ArrayList<NameValuePair>(parameters.size());

    for (Entry<String, List<String>> parameterEntry : parameters.entrySet()) {
        for (String value : parameterEntry.getValue()) {
            logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + value + "]");
            queryParameters.add(new BasicNameValuePair(parameterEntry.getKey(), value));
        }
    }

    HttpRequestBase httpMethod = null;
    HttpEntity httpEntity = null;
    URIBuilder uriBuilder = new URIBuilder(hostURI);

    // create the method
    if ("GET".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpGet(uriBuilder.build());
    } else if ("POST".equalsIgnoreCase(method)) {
        if (isMultipart) {
            logger.debug("setting multipart file content");
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                FileUtils.writeStringToFile(tempFile, (String) content, contentType.getCharset(), false);
            } else {
                FileUtils.writeByteArrayToFile(tempFile, (byte[]) content, false);
            }

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addPart(tempFile.getName(),
                    new FileBody(tempFile, contentType, tempFile.getName()));
            httpEntity = multipartEntityBuilder.build();
        } else if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPost(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("PUT".equalsIgnoreCase(method)) {
        if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPut(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPut(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("DELETE".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpDelete(uriBuilder.build());
    }

    if (httpMethod instanceof HttpEntityEnclosingRequestBase) {
        // Compress the request entity if necessary
        List<String> contentEncodingList = (List<String>) new CaseInsensitiveMap(headers)
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.toLowerCase().equals("gzip")
                        || contentEncoding.toLowerCase().equals("x-gzip"))) {
                    httpEntity = new GzipCompressingEntity(httpEntity);
                    break;
                }
            }
        }

        ((HttpEntityEnclosingRequestBase) httpMethod).setEntity(httpEntity);
    }

    // set the headers
    for (Entry<String, List<String>> headerEntry : headers.entrySet()) {
        for (String value : headerEntry.getValue()) {
            logger.debug("setting method header: [" + headerEntry.getKey() + ", " + value + "]");
            httpMethod.addHeader(headerEntry.getKey(), value);
        }
    }

    // Only set the Content-Type for entity-enclosing methods, but not if multipart is used
    if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && !isMultipart) {
        httpMethod.setHeader(HTTP.CONTENT_TYPE, contentType.toString());
    }

    return httpMethod;
}

From source file:com.mirth.connect.connectors.http.HttpSender.java

private boolean isUsingFormUrlEncoded(String contentType) {
    return StringUtils.startsWithIgnoreCase(contentType, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

/**
 * public for unit test, not to be used otherwise
 *///from  ww w . java  2 s . co m
public void execute(HttpUriRequest httpUriRequest, ContentType contentType,
        FutureCallback<HttpResponse> callback) {

    // add accept header when its not a form or multipart
    final String contentTypeString = contentType.toString();
    if (!ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType())
            && !contentType.getMimeType().startsWith(MULTIPART_MIME_TYPE)) {
        // otherwise accept what is being sent
        httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentTypeString);
    }
    // is something being sent?
    if (httpUriRequest instanceof HttpEntityEnclosingRequestBase
            && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
        httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    }

    // set user specified custom headers
    if (httpHeaders != null && !httpHeaders.isEmpty()) {
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpUriRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // add client protocol version if not specified
    if (!httpUriRequest.containsHeader(ODataHttpHeaders.DATASERVICEVERSION)) {
        httpUriRequest.addHeader(ODataHttpHeaders.DATASERVICEVERSION, ODataServiceVersion.V20);
    }
    if (!httpUriRequest.containsHeader(MAX_DATA_SERVICE_VERSION)) {
        httpUriRequest.addHeader(MAX_DATA_SERVICE_VERSION, ODataServiceVersion.V30);
    }

    // execute request
    client.execute(httpUriRequest, callback);
}

From source file:org.jboss.as.test.clustering.cluster.jsf.JSFFailoverTestCase.java

/**
 * Creates an HTTP POST request with a number guess.
 *
 * @param url//from   w w w.jav a 2s. com
 * @param sessionId
 * @param viewState
 * @param guess
 * @return
 * @throws UnsupportedEncodingException
 */
private static HttpUriRequest buildPostRequest(String url, String sessionId, String viewState, String guess)
        throws UnsupportedEncodingException {
    HttpPost post = new HttpPost(url);

    List<NameValuePair> list = new LinkedList<>();

    list.add(new BasicNameValuePair("javax.faces.ViewState", viewState));
    list.add(new BasicNameValuePair("numberGuess", "numberGuess"));
    list.add(new BasicNameValuePair("numberGuess:guessButton", "Guess"));
    list.add(new BasicNameValuePair("numberGuess:inputGuess", guess));

    post.setEntity(
            new StringEntity(URLEncodedUtils.format(list, "UTF-8"), ContentType.APPLICATION_FORM_URLENCODED));
    if (sessionId != null) {
        post.setHeader("Cookie", "JSESSIONID=" + sessionId);
    }

    return post;
}

From source file:org.jboss.as.test.integration.jsf.beanvalidation.cdi.BeanValidationCdiIntegrationTestCase.java

private String registerTeam(String name, int numberOfPeople) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();

    try {/*w  w w  .  ja  va  2s .c o m*/
        // Create and execute a GET request
        String jsfViewState = null;
        String requestUrl = url.toString() + "register.jsf";
        HttpGet getRequest = new HttpGet(requestUrl);
        HttpResponse response = client.execute(getRequest);
        try {
            String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

            // Get the JSF view state
            Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
            if (jsfViewMatcher.find()) {
                jsfViewState = jsfViewMatcher.group(1);
            }
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Create and execute a POST request with the given team name and
        // the given number of people
        HttpPost post = new HttpPost(requestUrl);

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
        list.add(new BasicNameValuePair("register", "register"));
        list.add(new BasicNameValuePair("register:inputName", name));
        list.add(new BasicNameValuePair("register:inputNumber", Integer.toString(numberOfPeople)));
        list.add(new BasicNameValuePair("register:registerButton", "Register"));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

        try {
            return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.jboss.as.test.integration.jsf.jsf23.JSF23SanityTestCase.java

@Test
public void testJSF23InjectCanBeUsed() throws Exception {
    String responseString;//w  ww .j av a 2  s  .  c  om
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        // Create and execute a GET request
        String jsfViewState = null;
        String requestUrl = url.toString() + "index.jsf";
        HttpGet getRequest = new HttpGet(requestUrl);
        HttpResponse response = client.execute(getRequest);
        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);

            // Get the JSF view state
            Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
            if (jsfViewMatcher.find()) {
                jsfViewState = jsfViewMatcher.group(1);
            }
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Create and execute a POST request
        HttpPost post = new HttpPost(requestUrl);

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
        list.add(new BasicNameValuePair("register", "register"));
        list.add(new BasicNameValuePair("register:registerButton", "Register"));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, StandardCharsets.UTF_8),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
    assertTrue(responseString.contains("JSF 2.3 Inject worked!"));
}

From source file:org.jboss.as.test.integration.jsf.managedbean.gc.GCPreDestroyTestCase.java

public void preDestroyCalled(String jsf) throws Exception {
    String responseString;//  w  ww  .  j a va  2s.  co  m
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        // Create and execute a GET request
        String jsfViewState = null;
        String requestUrl = url.toString();
        HttpGet getRequest = new HttpGet(requestUrl + jsf);

        HttpResponse response = client.execute(getRequest);
        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

            // Get the JSF view state
            Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
            if (jsfViewMatcher.find()) {
                jsfViewState = jsfViewMatcher.group(1);
            }

            assertTrue("PreDestroy initial value must be false", responseString.contains("IsPreDestroy:false"));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Create and execute a POST request
        HttpPost post = new HttpPost(requestUrl + jsf);

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
        list.add(new BasicNameValuePair("gcForm", "gcForm"));
        list.add(new BasicNameValuePair("gcForm:gcButton", "gc"));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }

    assertTrue("PreDestroy should have been invoked", responseString.contains("IsPreDestroy:true"));
}

From source file:org.opennms.protocols.http.HttpUrlConnection.java

@Override
public InputStream getInputStream() throws IOException {
    try {/* w  w  w .  j a  v  a  2 s .  co  m*/
        if (m_clientWrapper == null) {
            connect();
        }

        // Build URL
        int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort();
        URIBuilder ub = new URIBuilder();
        ub.setPort(port);
        ub.setScheme(m_url.getProtocol());
        ub.setHost(m_url.getHost());
        ub.setPath(m_url.getPath());
        if (m_url.getQuery() != null && !m_url.getQuery().trim().isEmpty()) {
            final List<NameValuePair> params = URLEncodedUtils.parse(m_url.getQuery(),
                    Charset.forName("UTF-8"));
            if (!params.isEmpty()) {
                ub.addParameters(params);
            }
        }

        // Build Request
        HttpRequestBase request = null;
        if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) {
            final Content cnt = m_request.getContent();
            HttpPost post = new HttpPost(ub.build());
            ContentType contentType = ContentType.create(cnt.getType());
            LOG.info("Processing POST request for {}", contentType);
            if (contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData());
                post.setEntity(fields.getEntity());
            } else {
                StringEntity entity = new StringEntity(cnt.getData(), contentType);
                post.setEntity(entity);
            }
            request = post;
        } else {
            request = new HttpGet(ub.build());
        }

        if (m_request != null) {
            // Add Custom Headers
            for (final Header header : m_request.getHeaders()) {
                request.addHeader(header.getName(), header.getValue());
            }
        }

        // Get Response
        CloseableHttpResponse response = m_clientWrapper.execute(request);
        return response.getEntity().getContent();
    } catch (Exception e) {
        throw new IOException(
                "Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(),
                e);
    }
}

From source file:org.wildfly.test.integration.ee8.temp.jsf23.JSF23SanityTestCase.java

@Test
public void testJSF23InjectCanBeUsed() throws Exception {
    String responseString;// w ww. ja v a  2  s  . c  om
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        // Create and execute a GET request
        String jsfViewState = null;
        String requestUrl = url.toString() + "index.jsf";
        HttpGet getRequest = new HttpGet(requestUrl);
        HttpResponse response = client.execute(getRequest);
        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

            // Get the JSF view state
            Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
            if (jsfViewMatcher.find()) {
                jsfViewState = jsfViewMatcher.group(1);
            }
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Create and execute a POST request
        HttpPost post = new HttpPost(requestUrl);

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
        list.add(new BasicNameValuePair("register", "register"));
        list.add(new BasicNameValuePair("register:registerButton", "Register"));

        post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

        try {
            responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
    assertTrue(responseString.contains("JSF 2.3 Inject worked!"));
}