Example usage for org.apache.http.client.fluent Executor execute

List of usage examples for org.apache.http.client.fluent Executor execute

Introduction

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

Prototype

public Response execute(final Request request) throws ClientProtocolException, IOException 

Source Link

Document

Executes the request.

Usage

From source file:org.apache.infra.reviewboard.ReviewBoard.java

public static void main(String... args) throws IOException {

    URL url = new URL(REVIEW_BOARD_URL);
    HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    Executor executor = Executor.newInstance().auth(host, REVIEW_BOARD_USERNAME, REVIEW_BOARD_PASSWORD)
            .authPreemptive(host);/*from w ww .  j  a va  2 s.  c om*/

    Request request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    Response response = executor.execute(request);

    request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    response = executor.execute(request);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readTree(response.returnResponse().getEntity().getContent());

    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out));
    generator.setPrettyPrinter(new DefaultPrettyPrinter());
    mapper.writeTree(generator, json);
}

From source file:interoperabilite.webservice.fluent.FluentExecutor.java

public static void main(String[] args) throws Exception {
    Executor executor = Executor.newInstance().auth(new HttpHost("somehost"), "username", "password")
            .auth(new HttpHost("myproxy", 8080), "username", "password")
            .authPreemptive(new HttpHost("myproxy", 8080));

    // Execute a GET with timeout settings and return response content as String.
    executor.execute(Request.Get("http://somehost/").connectTimeout(1000).socketTimeout(1000)).returnContent()
            .asString();/*  ww  w.  ja  va  2 s  .  c  o m*/

    // Execute a POST with the 'expect-continue' handshake, using HTTP/1.1,
    // containing a request body as String and return response content as byte array.
    executor.execute(Request.Post("http://somehost/do-stuff").useExpectContinue().version(HttpVersion.HTTP_1_1)
            .bodyString("Important stuff", ContentType.DEFAULT_TEXT)).returnContent().asBytes();

    // Execute a POST with a custom header through the proxy containing a request body
    // as an HTML form and save the result to the file
    executor.execute(Request.Post("http://somehost/some-form").addHeader("X-Custom-header", "stuff")
            .viaProxy(new HttpHost("myproxy", 8080))
            .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()))
            .saveContent(new File("result.dump"));
}

From source file:io.aos.protocol.http.httpcommon.FluentExecutor.java

public static void main(String... args) throws Exception {
    Executor executor = Executor.newInstance().auth(new HttpHost("somehost"), "username", "password")
            .auth(new HttpHost("myproxy", 8080), "username", "password")
            .authPreemptive(new HttpHost("myproxy", 8080));

    // Execute a GET with timeout settings and return response content as String.
    executor.execute(Request.Get("http://somehost/").connectTimeout(1000).socketTimeout(1000)).returnContent()
            .asString();// w w w  .j  a  v a  2s.  c  om

    // Execute a POST with the 'expect-continue' handshake, using HTTP/1.1,
    // containing a request body as String and return response content as byte array.
    executor.execute(Request.Post("http://somehost/do-stuff").useExpectContinue().version(HttpVersion.HTTP_1_1)
            .bodyString("Important stuff", ContentType.DEFAULT_TEXT)).returnContent().asBytes();

    // Execute a POST with a custom header through the proxy containing a request body
    // as an HTML form and save the result to the file
    executor.execute(Request.Post("http://somehost/some-form").addHeader("X-Custom-header", "stuff")
            .viaProxy(new HttpHost("myproxy", 8080))
            .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()))
            .saveContent(new File("result.dump"));
}

From source file:com.github.woki.payments.adyen.action.Endpoint.java

static <ResType extends Error, ReqType> ResType invoke(final ClientConfig config, final ReqType request,
        final Class<ResType> responseClass, final Options opts) throws IOException {
    Request httpRequest = createRequest(config, request, opts);
    Executor invoker = createExecutor(config);
    return invoker.execute(httpRequest).handleResponse(new ResponseHandler<ResType>() {
        public ResType handleResponse(HttpResponse response) throws IOException {
            ResType res = Endpoint.handleResponse(response, responseClass);
            if (LOG.isDebugEnabled()) {
                LOG.debug("response: {}", res);
            }/*from w ww  .  jav  a  2 s. c  o  m*/
            return res;
        }
    });
}

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

private static String readData(Executor exec, Request req, IProgressMonitor monitor) throws IOException {
    String obj = null;//from  w w  w  .  j a va  2  s. com
    ConnectionManager.register(monitor, req);
    try {
        obj = exec.execute(req).handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity entity = response.getEntity();
                InputStream in = null;
                String res = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    // System.out
                    // .println("---------------------------------------------------------------------------");
                    // System.out.println(response.toString());
                    // for (Header h : response.getAllHeaders()) {
                    // System.out.println(h.toString());
                    // }

                    switch (statusLine.getStatusCode()) {
                    case 200:
                        in = getContent(entity);
                        res = IOUtils.toString(in);
                        break;
                    default:
                        throw new HttpResponseException(statusLine.getStatusCode(),
                                statusLine.getReasonPhrase());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return res;
            }

            protected InputStream getContent(HttpEntity entity) throws ClientProtocolException, IOException {
                if (entity == null)
                    throw new ClientProtocolException("Response contains no content");
                return entity.getContent();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        ConnectionManager.unregister(req);
    }
    return obj;
}

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

/**
 * ???json?post?//from   w w w . j  a  va2  s .  c o  m
 * 
 * @throws IOException
 * @throws
 * 
 */
public static String fetchJsonHttpResponse(String contentUrl, Map<String, String> headerMap,
        JsonObject bodyJson) throws IOException {
    Executor executor = Executor.newInstance(httpClient);
    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 (bodyJson != null) {
        request.bodyString(bodyJson.toString(), ContentType.APPLICATION_JSON);
    }
    return executor.execute(request).returnContent().asString();
}

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

/**
 * ???json?post?/*  w w  w  . jav a2s  .  c  om*/
 *
 * @throws IOException
 *
 */
public static String fetchJsonHttpResponse(String contentUrl, Map<String, String> headerMap, String jsonBody)
        throws IOException {
    Executor executor = Executor.newInstance(httpClient);
    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 (jsonBody != null) {
        request.bodyString(jsonBody, ContentType.APPLICATION_JSON);
    }
    long start = System.currentTimeMillis();
    String response = executor.execute(request).returnContent().asString();
    logger.info("url = " + contentUrl + " request spend time = " + (System.currentTimeMillis() - start));
    return response;
}

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

/**
 * ?getpost????/*  www.  j  av  a  2 s .  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:com.github.sebhoss.camel.slack.webhook.SlackWebhookProcessor.java

@Override
public void process(final Exchange exchange) throws Exception {
    final String message = exchange.getIn().getBody(String.class);
    final String payload = payload(defaultName(exchange), message);
    final Executor executor = Executor.newInstance();

    executor.execute(Post(hook).bodyString(payload, APPLICATION_JSON));
}

From source file:org.wildfly.swarm.jaxrs.cdi.test.JaxrsCdiTest.java

private void sendRequestAndAssertCounter(Executor executor, int expectedCounter) throws IOException {
    String result = executor.execute(request).returnContent().asString();
    assertThat(result, containsString("Hello, Ladicek! Counter: " + expectedCounter));
}