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.loyalty.service.RemoteService.java

public KioskDTO activate() throws IOException, KioskException {
    try (CloseableHttpResponse result = getHttpClient().post("/public-api/activate",
            ContentType.APPLICATION_FORM_URLENCODED, new BasicNameValuePair("kioskLicense", license))) {
        if (result.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new KioskException(result.getStatusLine().getStatusCode(),
                    "Can't activate Kiosk with provided license code: " + getLicense());
        }//  w w w.j  a  v  a  2s  . c  o m
        kioskDTO = getMapper().readValue(EntityUtils.toString(result.getEntity()), KioskDTO.class);
        return kioskDTO;
    }
}

From source file:org.wildfly.swarm.examples.camel.mail.CamelMailIT.java

@Test
public void testIt() throws Exception {

    Thread.sleep(5000);//from  ww w.j  a v a 2 s .c  o  m

    Log log = getStdOutLog();
    assertThatLog(log).hasLineContaining("Bound camel naming object: java:jboss/camel/context/mail-context");
    assertThatLog(log).hasLineContaining("Bound mail session [java:jboss/mail/greenmail]");

    String response = Request.Post("http://localhost:8080/mail")
            .bodyString("Hello from camel!", ContentType.APPLICATION_FORM_URLENCODED).execute().returnContent()
            .asString();

    Assert.assertEquals(response, "Email sent to user1@localhost");
}

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

public static void setup(final Interpreter interpreter, final HttpRequest request, final HttpResponse response,
        final HttpSessionContext context) throws EvalError, IOException {
    ////ww w  .j  a va 2 s.c o  m
    // Set attributes as script variables
    //
    for (String k : context.keySet()) {
        String key = normalizeVariableName(k);
        interpreter.set(key, context.getAttribute(k));
    }

    //
    // If the request contains url-encoded body, set the given parameters
    //
    Header[] headers = request.getHeaders(HttpHeaders.CONTENT_TYPE);
    if (headers.length > 0) {
        String contentType = headers[0].getValue();
        if (contentType.matches(ContentType.APPLICATION_FORM_URLENCODED.getMimeType() + "( *;.*)?")) {
            HttpEntityEnclosingRequest r = (HttpEntityEnclosingRequest) request;
            HttpEntity e = r.getEntity();

            QueryString qs = QueryString.parse(IOUtils.toString(e.getContent()));
            for (String n : qs.getNames()) {
                String name = normalizeVariableName(n);
                interpreter.set(name, qs.getValues(n).get(0));
            }
        }
    }

    //
    // Set request parameters as script variables. Note that parameters
    // override attributes (note that these override form content
    //
    try {
        QueryString qs = QueryString.parse(new URI(request.getRequestLine().getUri()));
        for (String n : qs.getNames()) {
            String name = normalizeVariableName(n);
            interpreter.set(name, qs.getValues(n).get(0));
        }
    } catch (URISyntaxException x) {
        //
        // nothing to do
        //
    }

    BasicHttpConnection connection = (BasicHttpConnection) context
            .getAttribute(HttpCoreContext.HTTP_CONNECTION);

    interpreter.set(VAR_REQUEST, request);
    interpreter.set(VAR_RESPONSE, response);
    interpreter.set(VAR_SESSION, context);
    interpreter.set(VAR_OUT, connection.getWriter());
    interpreter.set(VAR_LOG, log);
    if (HttpUtils.hasJSONBody(request) && (request instanceof HttpEntityEnclosingRequest)) {
        interpreter.set(VAR_BODY, getJSONBody(getEntityInputStream(request)));
    }
}

From source file:com.loyalty.service.RemoteService.java

public CardDTO cardDetails(String cardNumber) throws IOException, KioskException {
    try (CloseableHttpResponse result = getHttpClient().post("/public-api/card",
            ContentType.APPLICATION_FORM_URLENCODED, new BasicNameValuePair("number", cardNumber))) {
        if (result.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new KioskException(result.getStatusLine().getStatusCode(),
                    "Can't find card by card number: " + cardNumber);
        }/*from   w  w w  .  j ava2  s  .  c o  m*/
        final CardDTO cardDTO = getMapper().readValue(EntityUtils.toString(result.getEntity()), CardDTO.class);
        return cardDTO;
    }
}

From source file:com.sangupta.jerry.oauth.service.impl.TwitterOAuthServiceImpl.java

@Override
protected void massageAuthorizationRequest(WebRequest request, WebForm webForm, TokenAndUrl tokenAndUrl,
        String verifier) {/* w  w w  .  j av a2 s .c o m*/
    request.bodyString(OAuthConstants.VERIFIER + "=" + verifier, ContentType.APPLICATION_FORM_URLENCODED);
}

From source file:com.haulmont.cuba.web.security.idp.IdpSessionPingConnector.java

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

    String idpBaseURL = webIdpConfig.getIdpBaseURL();
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }//w ww .ja v  a  2 s .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", webIdpConfig.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 == 410) {
            // we have to logout user
            log.debug("IDP session is expired {}", idpSessionId);

            if (userSessionSource.checkCurrentUserSession()) {
                authenticationService.logout();

                UserSession userSession = userSessionSource.getUserSession();

                throw new NoUserSessionException(userSession.getId());
            }
        }
        if (statusCode != 200) {
            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();
    }
}

From source file:es.upm.oeg.examples.watson.service.LanguageIdentificationService.java

public String getLang(String text) throws IOException, URISyntaxException {

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("txt", text));
    qparams.add(new BasicNameValuePair("sid", "lid-generic"));
    qparams.add(new BasicNameValuePair("rt", "json"));

    Executor executor = Executor.newInstance().auth(username, password);

    URI serviceURI = new URI(baseURL).normalize();
    String auth = username + ":" + password;
    String resp = executor.execute(Request.Post(serviceURI)
            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
            .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED))
            .returnContent().asString();

    JSONObject lang = JSONObject.parse(resp);

    return lang.get("lang").toString();

}

From source file:fr.ippon.wip.http.request.PostRequestBuilder.java

public HttpRequestBase buildHttpRequest() throws URISyntaxException {
    URI uri = new URI(getRequestedURL());
    HttpPost postRequest = new HttpPost(uri);
    if (parameterMap == null)
        return postRequest;

    List<NameValuePair> httpParams = new LinkedList<NameValuePair>();
    for (Map.Entry<String, String> entry : parameterMap.entries())
        httpParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

    HttpEntity formEntity = new UrlEncodedFormEntity(httpParams,
            ContentType.APPLICATION_FORM_URLENCODED.getCharset());
    postRequest.setEntity(formEntity);//w  w  w . ja va2s  .c  o  m

    return postRequest;
}

From source file:com.loyalty.service.RemoteService.java

@Override
public CardDTO checkIn(String cardNumber) throws IOException, KioskException {
    try (CloseableHttpResponse result = getHttpClient().post("/public-api/checkin",
            ContentType.APPLICATION_FORM_URLENCODED, new BasicNameValuePair("kioskLicense", getLicense()),
            new BasicNameValuePair("cardNumber", cardNumber))) {
        if (result.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new KioskException(result.getStatusLine().getStatusCode(),
                    "Can't find card by card number: " + cardNumber);
        }//w w w . ja v a  2s  .  c o m
        final CardDTO cardDTO = getMapper().readValue(EntityUtils.toString(result.getEntity()), CardDTO.class);
        return cardDTO;
    }
}

From source file:es.upm.oeg.examples.watson.service.MachineTranslationService.java

public String translate(String text, String sid) throws IOException, URISyntaxException {

    logger.info("Text to translate :" + text);
    logger.info("Translation type :" + sid);

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("txt", text));
    qparams.add(new BasicNameValuePair("sid", sid));
    qparams.add(new BasicNameValuePair("rt", "text"));

    Executor executor = Executor.newInstance();
    URI serviceURI = new URI(baseURL).normalize();
    String auth = username + ":" + password;
    byte[] responseB = executor.execute(Request.Post(serviceURI)
            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
            .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED))
            .returnContent().asBytes();//from   w w  w. j  a  va  2  s.com

    String response = new String(responseB, "UTF-8");

    logger.info("Translation response :" + response);

    return response;

}