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.sugarcrm.candybean.webservices.WSSystemTest.java

License:asdf

@Test
public void testPutRequestsFormData() {
    String formData = "test=asdf";
    try {//www. j av  a 2  s.  c o  m
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        response = WS.request(WS.OP.PUT, uri + "/put", headers, formData,
                ContentType.APPLICATION_FORM_URLENCODED);
    } catch (Exception e) {
        Assert.fail(e.toString());
    }
    Assert.assertTrue(response != null);
    Assert.assertEquals("asdf", ((Map) response.get("form")).get("test"));
}

From source file:com.haulmont.restapi.idp.IdpAuthLifecycleManager.java

protected IdpSessionStatus pingIdpSessionServer(String idpSessionId) {
    log.debug("Ping IDP session {}", idpSessionId);

    String idpBaseURL = idpConfig.getIdpBaseURL();
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }//w  w  w  .  j  a  v a 2s . co m
    String idpSessionPingUrl = idpBaseURL + "service/ping";

    HttpPost httpPost = new HttpPost(idpSessionPingUrl);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
            Arrays.asList(new BasicNameValuePair("idpSessionId", idpSessionId),
                    new BasicNameValuePair("trustedServicePassword", idpConfig.getIdpTrustedServicePassword())),
            StandardCharsets.UTF_8);

    httpPost.setEntity(formEntity);

    HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
    HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();

    try {
        HttpResponse httpResponse = client.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.GONE.value()) {
            log.debug("IDP session expired {}", idpSessionId);

            return IdpSessionStatus.EXPIRED;
        }
        if (statusCode != HttpStatus.OK.value()) {
            log.warn("IDP respond status {} on session ping", statusCode);
        }
    } catch (IOException e) {
        log.warn("Unable to ping IDP {} session {}", idpSessionPingUrl, idpSessionId, e);
    } finally {
        connectionManager.shutdown();
    }

    return IdpSessionStatus.ALIVE;
}

From source file:photosharing.api.oauth.OAuth20Handler.java

/**
 * renews an access token with the user's data
 * /*from w w  w . j  a va2  s  . c  om*/
 * @param oData
 *            the current OAuth 2.0 data.
 * @return {OAuth20Data} or null
 * @throws IOException
 */
public OAuth20Data renewAccessToken(OAuth20Data oData) throws IOException {
    logger.finest("renewAccessToken activated");

    Configuration config = Configuration.getInstance(null);
    String body = this.generateRenewAccessTokenRequestBody(oData.getAccessToken(), oData.getRefreshToken(),
            oData.getIssuedOn(), oData.getExpiresIn());

    // 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:com.haulmont.cuba.web.security.idp.BaseIdpSessionFilter.java

@Nullable
protected IdpSession getIdpSession(String idpTicket) throws IdpActivationException {
    String idpBaseURL = webIdpConfig.getIdpBaseURL();
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }//from  ww w .j  a  v  a  2 s .  c o  m
    String idpTicketActivateUrl = idpBaseURL + "service/activate";

    HttpPost httpPost = new HttpPost(idpTicketActivateUrl);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
            Arrays.asList(new BasicNameValuePair("serviceProviderTicket", idpTicket), new BasicNameValuePair(
                    "trustedServicePassword", webIdpConfig.getIdpTrustedServicePassword())),
            StandardCharsets.UTF_8);

    httpPost.setEntity(formEntity);

    HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
    HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();

    String idpResponse;
    try {
        HttpResponse httpResponse = client.execute(httpPost);

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == 410) {
            // used old ticket
            return null;
        }

        if (statusCode != 200) {
            throw new IdpActivationException("Idp respond with status " + statusCode);
        }

        idpResponse = new BasicResponseHandler().handleResponse(httpResponse);
    } catch (IOException e) {
        throw new IdpActivationException(e);
    } finally {
        connectionManager.shutdown();
    }

    IdpSession session;
    try {
        session = new Gson().fromJson(idpResponse, IdpSession.class);
    } catch (JsonSyntaxException e) {
        throw new IdpActivationException("Unable to parse idp response", e);
    }

    return session;
}

From source file:com.haulmont.restapi.idp.IdpAuthController.java

@Nullable
protected IdpSession getIdpSession(String idpTicket) throws InvalidGrantException {
    String idpBaseURL = this.idpBaseURL;
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }//from w w w.j a va 2  s . c  om
    String idpTicketActivateUrl = idpBaseURL + "service/activate";

    HttpPost httpPost = new HttpPost(idpTicketActivateUrl);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
            Arrays.asList(new BasicNameValuePair("serviceProviderTicket", idpTicket),
                    new BasicNameValuePair("trustedServicePassword", idpTrustedServicePassword)),
            StandardCharsets.UTF_8);

    httpPost.setEntity(formEntity);

    HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
    HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();

    String idpResponse;
    try {
        HttpResponse httpResponse = client.execute(httpPost);

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == 410) {
            // used old ticket
            return null;
        }

        if (statusCode != 200) {
            throw new RuntimeException("Idp respond with status " + statusCode);
        }

        idpResponse = new BasicResponseHandler().handleResponse(httpResponse);
    } catch (IOException e) {
        throw new RuntimeException("Unable to connect to IDP", e);
    } finally {
        connectionManager.shutdown();
    }

    IdpSession session;
    try {
        session = new Gson().fromJson(idpResponse, IdpSession.class);
    } catch (JsonSyntaxException e) {
        throw new RuntimeException("Unable to parse idp response", e);
    }

    return session;
}

From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java

@Test
public void formUrlEncodedParameters() throws Exception {
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("get", TEST_URI09);
    StringEntity e = new StringEntity(TEST_QUERY_STRING);
    e.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
    request.setEntity(e);/*from w  w w. j  ava  2  s. c om*/

    HttpSessionContext context = new HttpSessionContext();
    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    request.addHeader(HTTP.CONTENT_TYPE, e.getContentType().getValue());

    Interpreter i = new Interpreter();
    BeanShellUtils.setup(i, request, RESPONSE_OK, context);

    then(i.get(TEST_URL_PARAM1)).isEqualTo(TEST_VALUE1);
    then(i.get(TEST_URL_PARAM2)).isEqualTo(TEST_VALUE2);

    e.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType() + " ; charset=UTF-8");
    request.setHeader(HTTP.CONTENT_TYPE, e.getContentType().getValue());

    i = new Interpreter();
    BeanShellUtils.setup(i, request, RESPONSE_OK, context);

    then(i.get(TEST_URL_PARAM1)).isEqualTo(TEST_VALUE1);
    then(i.get(TEST_URL_PARAM2)).isEqualTo(TEST_VALUE2);

}

From source file:com.lonepulse.zombielink.request.FormParamProcessor.java

/**
 * <p>Accepts the {@link InvocationContext} with an {@link HttpEntityEnclosingRequestBase} and 
 * creates a list of <a href="http://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms">
 * form-urlencoded</a> name-value pairs using arguments annotated with @{@link FormParam} and 
 * @{@link FormParams}. It's then inserted to the body of the request being processed.</p>
 * //from   w  ww.  ja va2 s .  com
 * <p><b>Note</b> that any {@link HttpRequestBase}s which aren't {@link HttpEntityEnclosingRequestBase}s 
 * will be ignored.</p>
 * 
 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
 * 
 * @param context
 *          the {@link InvocationContext} which is used to discover any annotated form parameters 
 * <br><br>
 * @param request
 *          prefers an instance of {@link HttpPost} so as to conform with HTTP 1.1; however, other  
 *          {@link HttpEntityEnclosingRequestBase}s will be entertained to allow compliance with 
 *          unusual endpoint definitions (as long as they are {@link HttpEntityEnclosingRequestBase}s) 
 * <br><br>
  * @return the same instance of {@link HttpRequestBase} which was given for processing form parameters 
 * <br><br>
 * @throws RequestProcessorException
 *          if a form parameters failed to be created and inserted into the request body
 * <br><br>
 * @since 1.3.0
 */
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {

    try {

        if (request instanceof HttpEntityEnclosingRequestBase) {

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

            //add static name and value pairs
            List<Param> constantFormParams = RequestUtils.findStaticFormParams(context);

            for (Param param : constantFormParams) {

                nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));
            }

            //add individual name and value pairs
            List<Entry<FormParam, Object>> formParams = Metadata.onParams(FormParam.class, context);

            for (Entry<FormParam, Object> entry : formParams) {

                String name = entry.getKey().value();
                Object value = entry.getValue();

                if (!(value instanceof CharSequence)) {

                    StringBuilder errorContext = new StringBuilder()
                            .append("Form (url-encoded) parameters can only be of type ")
                            .append(CharSequence.class.getName())
                            .append(". Please consider implementing CharSequence ")
                            .append("and providing a meaningful toString() representation for the ")
                            .append("<name> of the form parameter. ");

                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }

                nameValuePairs.add(new BasicNameValuePair(name, String.valueOf(value)));
            }

            //add batch name and value pairs (along with any static params)
            List<Entry<FormParams, Object>> queryParamMaps = Metadata.onParams(FormParams.class, context);

            for (Entry<FormParams, Object> entry : queryParamMaps) {

                Param[] constantParams = entry.getKey().value();

                if (constantParams != null && constantParams.length > 0) {

                    for (Param param : constantParams) {

                        nameValuePairs.add(new BasicNameValuePair(param.name(), param.value()));
                    }
                }

                Object map = entry.getValue();

                if (!(map instanceof Map)) {

                    StringBuilder errorContext = new StringBuilder()
                            .append("@FormParams can only be applied on <java.util.Map>s. ")
                            .append("Please refactor the method to provide a Map of name and value pairs. ");

                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }

                Map<?, ?> nameAndValues = (Map<?, ?>) map;

                for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) {

                    Object name = nameAndValue.getKey();
                    Object value = nameAndValue.getValue();

                    if (!(name instanceof CharSequence
                            && (value instanceof CharSequence || value instanceof Collection))) {

                        StringBuilder errorContext = new StringBuilder().append(
                                "The <java.util.Map> identified by @FormParams can only contain mappings of type ")
                                .append("<java.lang.CharSequence, java.lang.CharSequence> or ")
                                .append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>");

                        throw new RequestProcessorException(
                                new IllegalArgumentException(errorContext.toString()));
                    }

                    if (value instanceof CharSequence) {

                        nameValuePairs.add(new BasicNameValuePair(((CharSequence) name).toString(),
                                ((CharSequence) value).toString()));
                    } else { //add multi-valued form params 

                        Collection<?> multivalues = (Collection<?>) value;

                        for (Object multivalue : multivalues) {

                            if (!(multivalue instanceof CharSequence)) {

                                StringBuilder errorContext = new StringBuilder().append(
                                        "Values for the <java.util.Map> identified by @FormParams can only contain collections ")
                                        .append("of type java.util.Collection<? extends CharSequence>");

                                throw new RequestProcessorException(
                                        new IllegalArgumentException(errorContext.toString()));
                            }

                            nameValuePairs.add(new BasicNameValuePair(((CharSequence) name).toString(),
                                    ((CharSequence) multivalue).toString()));
                        }
                    }
                }
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
            urlEncodedFormEntity.setContentType(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

            request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }

        return request;
    } catch (Exception e) {

        throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e
                : new RequestProcessorException(context, getClass(), e);
    }
}

From source file:com.github.zhizheng.jenkins.JenkinsServiceImpl.java

@Override
public void createCredentialsByJson(String id, String username, String password, String desc)
        throws JenkinsException {
    try {//from   ww w  . j a va2  s .c o m
        JenkinsHttpClient client = new JenkinsHttpClient(new URI(jenkinsUrl), jenkinsUser, jenkinsPassword);
        String req = "json={\"\":\"0\",\"credentials\":{\"scope\":\"GLOBAL\",\"username\":\"" + username
                + "\",\"password\":\"" + password + "\",\"id\":\"" + id + "\",\"description\":\"" + desc
                + "\",\"$class\":\"com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl\"}}";
        client.post_text("credentials/store/system/domain/_/createCredentials", req,
                ContentType.APPLICATION_FORM_URLENCODED, true);
    } catch (Exception e) {
        throw new JenkinsException(e);
    }
}