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:photosharing.api.oauth.OAuth20Handler.java

/**
 * gets an access token based on the code
 * /*from  www.  j a  v  a2  s  . co  m*/
 * @param code
 *            - the >254 character code representing temporary credentials
 * @return the OAuth 20 configuration for the user requesting
 * @throws IOException
 */
public OAuth20Data getAccessToken(String code) throws IOException {
    logger.info("getAccessToken activated");
    OAuth20Data oData = null;

    Configuration config = Configuration.getInstance(null);
    String body = this.generateAccessTokenRequestBody(config.getValue(Configuration.CLIENTID),
            config.getValue(Configuration.CLIENTSECRET), config.getValue(Configuration.CALLBACKURL), code);

    // Builds the URL in a StringBuilder
    StringBuilder builder = new StringBuilder();
    builder.append(config.getValue(Configuration.BASEURL));
    builder.append(TOKENURL);

    Request post = Request.Post(builder.toString());
    post.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
    post.body(new StringEntity(body));

    /**
     * Block is executed if there is a trace
     */
    logger.info("URL Encoded body is " + body);
    logger.info("Token URL is " + builder.toString());

    /**
     * Executes with a wrapped executor
     */
    Executor exec = ExecutorUtil.getExecutor();
    Response apiResponse = exec.execute(post);
    HttpResponse hr = apiResponse.returnResponse();

    /**
     * Check the status codes and if 200, convert to String and process the
     * response body
     */
    int statusCode = hr.getStatusLine().getStatusCode();

    if (statusCode == 200) {
        InputStream in = hr.getEntity().getContent();
        String x = IOUtils.toString(in);
        oData = OAuth20Data.createInstance(x);
    } else {
        logger.warning("OAuth20Data status code " + statusCode);
    }

    return oData;
}

From source file:org.apromore.plugin.deployment.yawl.YAWLEngineClient.java

private String sendRequestToYAWL(final String request) throws DeploymentException {
    try {/*from   ww  w.  ja  v  a  2s .c  o m*/
        return Request.Post(engineUrl).useExpectContinue().addHeader("Accept-Charset", ENCODING)
                .version(HttpVersion.HTTP_1_1).bodyString(request, ContentType.APPLICATION_FORM_URLENCODED)
                .execute().returnContent().asString();
    } catch (IOException e) {
        throw new DeploymentException("Request to YAWL engine failed.", e);
    }
}

From source file:com.ibm.watson.WatsonTranslate.java

public String translate(String text) {
    String tweetTranslation = text;

    if (watsonLangPair != null && text != null && !text.equals("")) {
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("txt", text));
        qparams.add(new BasicNameValuePair("sid", watsonLangPair));
        qparams.add(new BasicNameValuePair("rt", "text"));

        try {//w  w  w  . jav  a 2  s  . com
            Executor executor = Executor.newInstance();
            URI serviceURI = new URI(baseURLTranslation).normalize();
            String auth = usernameTranslation + ":" + passwordTranslation;
            byte[] response = executor
                    .execute(Request.Post(serviceURI)
                            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
                            .bodyString(URLEncodedUtils.format(qparams, "utf-8"),
                                    ContentType.APPLICATION_FORM_URLENCODED)
                            .connectTimeout(15 * 1000))
                    .returnContent().asBytes();

            tweetTranslation = new String(response, "UTF-8");
            logger.debug("Translated {} to {}", text, tweetTranslation);
        } catch (Exception e) {
            logger.error("Watson error: {} on text: {}", e.getMessage(), text);
        }
    }

    return tweetTranslation;
}

From source file:org.jboss.as.test.integration.jsf.doctype.DoctypeDeclTestCase.java

private String register(String name, int expectedStatusCode) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();

    try {/*w w  w . j a  v  a 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 {
            // Get the JSF view state
            String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
            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 name
        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:registerButton", "Register"));
        post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"),
                ContentType.APPLICATION_FORM_URLENCODED));
        response = client.execute(post);

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

From source file:com.arpnetworking.tsdcore.sinks.MonitordSink.java

/**
 * {@inheritDoc}/* w w  w. j  ava 2s  .co m*/
 */
@Override
protected HttpUriRequest createRequest(final String serializedData) {
    final StringEntity requestEntity = new StringEntity(serializedData,
            ContentType.APPLICATION_FORM_URLENCODED);
    final HttpPost request = new HttpPost(getUri());
    request.setEntity(requestEntity);
    return request;
}

From source file:org.apache.brooklyn.rest.BrooklynPropertiesSecurityFilterTest.java

@Test(groups = { "Integration", "Broken" })
public void testInteractionOfSecurityFilterAndFormMapProvider() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {/*from  w  w  w.  j av  a  2  s. com*/
        Server server = useServerForTest(
                BrooklynRestApiLauncher.launcher().securityProvider(AnyoneSecurityProvider.class)
                        .forceUseOfDefaultCatalogWithJavaClassPath(true).withoutJsgui().start());
        String appId = startAppAtNode(server);
        String entityId = getTestEntityInApp(server, appId);
        HttpClient client = HttpTool.httpClientBuilder().uri(getBaseUri(server)).build();
        List<? extends NameValuePair> nvps = Lists.newArrayList(new BasicNameValuePair("arg", "bar"));
        String effector = String.format("/v1/applications/%s/entities/%s/effectors/identityEffector", appId,
                entityId);
        HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUri() + effector),
                ImmutableMap.of(HttpHeaders.CONTENT_TYPE,
                        ContentType.APPLICATION_FORM_URLENCODED.getMimeType()),
                URLEncodedUtils.format(nvps, Charsets.UTF_8).getBytes());

        LOG.info("Effector response: {}", response.getContentAsString());
        assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()),
                "response code=" + response.getResponseCode());
    } finally {
        LOG.info("testInteractionOfSecurityFilterAndFormMapProvider complete in "
                + Time.makeTimeStringRounded(stopwatch));
    }
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

private HttpEntity createEntity(HttpServletRequest servletRequest) throws IOException {
    final String contentType = servletRequest.getContentType();
    // body with 'application/x-www-form-urlencoded' is handled by tomcat therefore we cannot
    // obtain it through input stream and need some workaround
    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
        List<NameValuePair> entries = new ArrayList<>();
        // obviously that we also copy params from url, but we cannot differentiate its
        Enumeration<String> names = servletRequest.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            entries.add(new BasicNameValuePair(name, servletRequest.getParameter(name)));
        }/* w w w  . ja  v a  2s .  co  m*/
        return new UrlEncodedFormEntity(entries, servletRequest.getCharacterEncoding());
    }

    // Add the input entity (streamed)
    //  note: we don't bother ensuring we close the servletInputStream since the container handles it
    return new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength(),
            ContentType.create(contentType));
}

From source file:org.ow2.proactive.procci.service.RequestUtils.java

/**
 * Send a service to the scheduler with the name and the password from the configuration file in order to get the
 * session id//ww  w  .j a  v  a  2 s . c o  m
 *
 * @return the session id
 */
public String getSessionId() {
    final String SCHEDULER_LOGIN_URL = getProperty("scheduler.login.endpoint");
    final String SCHEDULER_REQUEST = "username=" + getProperty("login.name") + "&password="
            + getProperty("login.password");

    try {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost postRequest = new HttpPost(SCHEDULER_LOGIN_URL);
        StringEntity input = new StringEntity(SCHEDULER_REQUEST, ContentType.APPLICATION_FORM_URLENCODED);
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        return readHttpResponse(response, SCHEDULER_LOGIN_URL, SCHEDULER_REQUEST);
    } catch (IOException ex) {
        logger.error("Unable to get the session id", ex);
        logError(SCHEDULER_LOGIN_URL, SCHEDULER_REQUEST);
        throw new ServerException();
    }

}