Example usage for org.apache.http.client.fluent Form add

List of usage examples for org.apache.http.client.fluent Form add

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Form add.

Prototype

public Form add(final String name, final String value) 

Source Link

Usage

From source file:es.uvigo.esei.dai.hybridserver.utils.TestUtils.java

private static List<NameValuePair> mapToNameValuePair(Map<String, String> map) {
    final Form form = Form.form();

    for (Map.Entry<String, String> entry : map.entrySet()) {
        form.add(entry.getKey(), entry.getValue());
    }/* w ww.  j a v a2  s  .  c o m*/

    return form.build();
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * ?getpost????/*from  w ww. j  a v  a 2s  . c  o  m*/
 */
public static String fetchSimpleHttpResponse(String method, String contentUrl, Map<String, String> headerMap,
        Map<String, String> bodyMap) throws IOException {
    Executor executor = Executor.newInstance(httpClient);
    if (HttpGet.METHOD_NAME.equalsIgnoreCase(method)) {
        String result = contentUrl;
        StringBuilder sb = new StringBuilder();
        sb.append(contentUrl);
        if (bodyMap != null && !bodyMap.isEmpty()) {
            if (contentUrl.indexOf("?") > 0) {
                sb.append("&");
            } else {
                sb.append("?");
            }
            result = Joiner.on("&").appendTo(sb, bodyMap.entrySet()).toString();
        }

        return executor.execute(Request.Get(result)).returnContent().asString();
    }
    if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
        Request request = Request.Post(contentUrl);
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> m : headerMap.entrySet()) {
                request.addHeader(m.getKey(), m.getValue());
            }
        }
        if (bodyMap != null && !bodyMap.isEmpty()) {
            Form form = Form.form();
            for (Map.Entry<String, String> m : bodyMap.entrySet()) {
                form.add(m.getKey(), m.getValue());
            }
            request.bodyForm(form.build());
        }
        return executor.execute(request).returnContent().asString();
    }
    return null;

}

From source file:org.kie.smoke.wb.util.RestUtil.java

public static <T> T postForm(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Map<String, String> formParams, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    // form content
    Form formContent = Form.form();
    for (Entry<String, String> entry : formParams.entrySet()) {
        formContent.add(entry.getKey(), entry.getValue());
    }/*from   w w  w .j  a  v  a  2  s.c  o  m*/

    // @formatter:off
    Request request = Request.Post(uriStr).addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString())
            .addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password))
            .bodyForm(formContent.build());
    // @formatter:on

    Response resp = null;
    try {
        logOp("POST", uriStr);
        resp = request.execute();
    } catch (Exception e) {
        logAndFail("[GET] " + uriStr, e);
    }

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);
    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        logAndFail("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:org.kie.remote.tests.base.RestUtil.java

public static <T> T postForm(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Map<String, String> formParams, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    // form content
    Form formContent = Form.form();
    for (Entry<String, String> entry : formParams.entrySet()) {
        formContent.add(entry.getKey(), entry.getValue());
    }/*from   w  w  w.j  ava  2s.c o m*/

    // @formatter:off
    Request request = Request.Post(uriStr).addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString())
            .addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password))
            .bodyForm(formContent.build());
    // @formatter:on

    Response resp = null;
    long before = 0, after = 0;
    try {
        logOp("POST", uriStr);
        resp = request.execute();
    } catch (Exception e) {
        failAndLog("[GET] " + uriStr, e);
    }

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);
    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        failAndLog("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }/*from   w  w w.  j a v  a  2 s  .  c  om*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}

From source file:edu.jhuapl.dorset.http.apache.ApacheHttpClient.java

private List<NameValuePair> buildFormBody(HttpParameter[] parameters) {
    Form form = Form.form();
    for (HttpParameter param : parameters) {
        form.add(param.getName(), param.getValue());
    }/*from  w  w  w.ja  v  a 2 s  . c om*/
    return form.build();
}

From source file:hulop.cm.util.LogHelper.java

public JSONArray getLog(String clientId, String start, String end, String skip, String limit) throws Exception {
    if (mApiKey == null) {
        return new JSONArray();
    }/*from   w  w  w  .j av  a 2  s  .co m*/
    Form form = Form.form().add("action", "get").add("auditor_api_key", mApiKey).add("event", "conversation");
    if (clientId != null) {
        form.add("clientId", clientId);
    }
    if (start != null) {
        form.add("start", start);
    }
    if (end != null) {
        form.add("end", end);
    }
    if (skip != null) {
        form.add("skip", skip);
    }
    if (limit != null) {
        form.add("limit", limit);
    }
    Request request = Request.Post(new URI(mEndpoint)).bodyForm(form.build());
    return (new JSONArray(request.execute().returnContent().asString()));
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java

@Test
public void httpFormPostTest() throws Exception {

    FileReader fileReader = new FileReader(new File(samplesDir, "/http-form/form-data.json"));
    Map<String, ?> jsonMap = Utils.fromJsonToMap(fileReader, false);
    Utils.close(fileReader);// w ww . j  a  va 2  s. co m

    assertNotNull("Could not load form data from JSON", jsonMap);
    assertFalse("Loaded form data is empty", jsonMap.isEmpty());
    Form form = Form.form();

    for (Map.Entry<String, ?> e : jsonMap.entrySet()) {
        form.add(e.getKey(), String.valueOf(e.getValue()));
    }

    try {
        Thread.sleep(100);
        Request.Get(makeURI()).execute().returnContent();
    } catch (HttpResponseException ex) {

    }
    HttpResponse resp = Request.Post(makeURI()).version(HttpVersion.HTTP_1_1).bodyForm(form.build()).execute()
            .returnResponse();
    assertEquals(200, resp.getStatusLine().getStatusCode());
}

From source file:AIR.Common.Web.HttpWebHelper.java

public String submitForm3(String url, Map<String, Object> formParameters, int maxTries,
        _Ref<Integer> httpStatusCode) throws IOException {
    Form f = Form.form();
    for (Map.Entry<String, Object> entry : formParameters.entrySet())
        f.add(entry.getKey(), entry.getValue().toString());

    for (int i = 1; i <= maxTries; i++) {
        try {//from w ww. j  av  a2 s  .c o  m
            return Request.Post(url).staleConnectionCheck(true).connectTimeout(getTimeoutInMillis())
                    .socketTimeout(getTimeoutInMillis()).version(HttpVersion.HTTP_1_1).bodyForm(f.build())
                    .execute().returnContent().asString();
        } catch (Exception e) {
            httpStatusCode.set(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            if (i == maxTries)
                throw new IOException(e);
        }
    }

    // for some reason we ended here. just throw an exception.
    throw new IOException("Could not retrive result.");
}

From source file:de.elomagic.maven.http.HTTPMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    try {/*from   w ww . j a va  2s . c  o  m*/
        Executor executor;

        if (httpsInsecure) {
            getLog().info("Accepting unsecure HTTPS connections.");
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustAllStrategy());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

                final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslsf).build();

                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                        sfr);
                connectionManager.setDefaultMaxPerRoute(100);
                connectionManager.setMaxTotal(200);
                connectionManager.setValidateAfterInactivity(1000);

                HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                        .build();

                executor = Executor.newInstance(httpClient);
            } catch (Exception ex) {
                throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex);
            }
        } else {
            executor = Executor.newInstance();
        }

        Settings settings = session.getSettings();
        if (StringUtils.isNotBlank(serverId)) {
            Server server = settings.getServer(serverId);
            if (server == null) {
                throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml");
            }
            getLog().debug("ServerId: " + serverId);
            executor.auth(server.getUsername(), server.getPassword());
        }

        Request request = createRequestMethod();

        request.setHeader("Accept", accept);

        if (httpHeaders != null) {
            for (Entry<String, String> entry : httpHeaders.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (formParams != null) {
            Form form = Form.form();
            for (Entry<String, String> entry : formParams.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
        }

        if (fromFile != null) {
            if (!fromFile.exists()) {
                throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist.");
            }

            if (StringUtils.isBlank(contentType)) {
                contentType = Files.probeContentType(fromFile.toPath());
            }

            getLog().debug("From file: " + fromFile);
            getLog().debug("Upload file size: "
                    + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue()));
            getLog().debug("Content type: " + contentType);

            if (StringUtils.isBlank(contentType)) {
                request.body(new FileEntity(fromFile));
            } else {
                request.body(new FileEntity(fromFile, ContentType.create(contentType)));
            }
        }

        getLog().info(method + " " + url);

        Response response = executor.execute(request);
        handleResponse(response);
    } catch (Exception ex) {
        getLog().error(ex);
        if (failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            getLog().info("Fail on error is disabled. Continue execution.");
        }
    }

}