Example usage for org.apache.http.client.fluent Request addHeader

List of usage examples for org.apache.http.client.fluent Request addHeader

Introduction

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

Prototype

public Request addHeader(final String name, final String value) 

Source Link

Usage

From source file:org.apache.sling.replication.transport.impl.HttpTransportHandler.java

private static void addHeader(Request req, String header) {
    int idx = header.indexOf(":");
    if (idx < 0)
        return;// www  .  j a  va 2 s.com
    String headerName = header.substring(0, idx).trim();
    String headerValue = header.substring(idx + 1).trim();
    req.addHeader(headerName, headerValue);
}

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

private static Request createPost(APService service, ClientConfig config, Object request) {
    Request retval = Post(config.getEndpointPort(service));
    // configure conn timeout
    retval.connectTimeout(config.getConnectionTimeout());
    // configure socket timeout
    retval.socketTimeout(config.getSocketTimeout());
    // add json/*from  w w  w.j  av  a2 s  .c  o  m*/
    retval.addHeader("Content-Type", "application/json");
    retval.addHeader("Accept", "application/json");
    for (Map.Entry<String, String> entry : config.getExtraParameters().entrySet()) {
        retval.addHeader(entry.getKey(), entry.getValue());
    }
    // add content
    String bodyString;
    try {
        bodyString = MAPPER.writeValueAsString(encrypt(config, request));
    } catch (Exception e) {
        throw new RuntimeException("CSE/JSON serialization error", e);
    }
    retval.bodyString(bodyString, ContentType.APPLICATION_JSON);
    if (config.hasProxy()) {
        retval.viaProxy(config.getProxyHost());
    }
    return retval;
}

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

/**
 * ???json?post?/*from w w  w  .  j a  v  a  2  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?//from   w w w .  j  a va2 s  .  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????//from w ww  . j  ava2s .c om
 */
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.fuin.owndeb.commons.DebUtils.java

/**
 * Downloads a file from an URL to a file and outputs progress in the log
 * (level 'info') every 1000 bytes./* w  w  w.  ja  va2s. com*/
 * 
 * @param url
 *            URL to download.
 * @param dir
 *            Target directory.
 * @param cookies
 *            Cookies for the request (Format: "name=value").
 */
public static void download(@NotNull final URL url, @NotNull final File dir, final String... cookies) {
    Contract.requireArgNotNull("url", url);
    Contract.requireArgNotNull("dir", dir);

    LOG.info("Download: {}", url);

    try {
        final Request request = Request.Get(url.toURI());
        if (cookies != null) {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < cookies.length; i++) {
                if (i > 0) {
                    sb.append(";");
                }
                sb.append(cookies[i]);
            }
            request.addHeader("Cookie", sb.toString());
        }
        final File file = new File(dir, FilenameUtils.getName(url.getFile()));
        request.execute().saveContent(file);
    } catch (final IOException | URISyntaxException ex) {
        throw new RuntimeException("Error downloading: " + url, ex);
    }
}

From source file:com.ibm.watson.ta.retail.ImportHousingServlet.java

/**
 * Forward the request to the index.jsp file
 *
 * @param req the req/* w  w  w.ja  va 2 s.co m*/
 * @param resp the resp
 * @throws ServletException the servlet exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
protected void doGet(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    logger.info("forwarding...");

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL;
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();

        Request newReq = Request.Get(uri);
        newReq.addHeader("Authorization", "Basic c2ltcGx5cmV0czpzaW1wbHlyZXRz");
        logger.log(Level.SEVERE, "My custom log:" + queryStr);

        Executor executor = Executor.newInstance();
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:info.losd.galen.client.ApiClient.java

public ApiResponse execute(ApiRequest req) {
    try {/*from ww w.  j a v a  2s  .  c o m*/
        Request request = request(req);

        req.getHeaders().forEach((header, value) -> request.addHeader(header, value));

        long start = System.nanoTime();
        HttpResponse response = request.execute().returnResponse();
        long end = System.nanoTime();

        HealthcheckDetails stat = HealthcheckDetails.tag(req.getTag()).duration((end - start) / 1000000)
                .statusCode(response.getStatusLine().getStatusCode()).build();
        healthcheckRepo.save(stat);

        return ApiResponse.statusCode(response.getStatusLine().getStatusCode()).body(getResponseBody(response))
                .build();
    } catch (IOException e) {
        logger.error("IO Exception", e);
        throw new RuntimeException(e);
    }
}

From source file:com.github.aistomin.http.PostRequest.java

@Override
public String execute() throws Exception {
    final Request request = Request.Post(this.resource);
    for (final Map.Entry<String, String> item : this.heads.entrySet()) {
        request.addHeader(item.getKey(), item.getValue());
    }//  w  w  w  .java2  s.c om
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setRedirectStrategy(new LaxRedirectStrategy());
    builder.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
        public boolean retryRequest(final HttpResponse response, final int count, final HttpContext context) {
            return count <= PostRequest.RETRY_COUNT;
        }

        public long getRetryInterval() {
            return PostRequest.RETRY_INTERVAL;
        }
    });
    return Executor.newInstance(builder.build()).execute(request).returnContent().asString();
}

From source file:io.gravitee.gateway.standalone.DynamicRoutingGatewayTest.java

@Test
public void call_dynamic_api() throws Exception {
    String initialTarget = api.getProxy().getEndpoints().get(0).getTarget();
    String dynamicTarget = create(URI.create("http://localhost:8080/team"), new URL(initialTarget).getPort())
            .toString();//from w  ww.  j  a v  a 2 s.com

    org.apache.http.client.fluent.Request request = org.apache.http.client.fluent.Request
            .Get("http://localhost:8082/test/my_team");
    request.addHeader("X-Dynamic-Routing-URI", dynamicTarget);

    org.apache.http.client.fluent.Response response = request.execute();
    HttpResponse returnResponse = response.returnResponse();

    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());
}