Example usage for org.apache.http.client.methods HttpUriRequest addHeader

List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader

Introduction

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

Prototype

void addHeader(String str, String str2);

Source Link

Usage

From source file:org.fcrepo.integration.connector.file.FileConnectorIT.java

private CloseableDataset getDataset(final CloseableHttpClient client, final HttpUriRequest req)
        throws IOException {
    if (!req.containsHeader("Accept")) {
        req.addHeader("Accept", "application/n-triples");
    }//from w  w w  .j  a  v a  2  s  .  co  m
    logger.debug("Retrieving RDF using mimeType: {}", req.getFirstHeader("Accept"));

    try (final CloseableHttpResponse response = client.execute(req)) {
        assertEquals(OK.getStatusCode(), response.getStatusLine().getStatusCode());
        final CloseableDataset result = parseTriples(response.getEntity());
        logger.trace("Retrieved RDF: {}", result);
        return result;
    }
}

From source file:org.ambraproject.wombat.service.remote.CachedRemoteService.java

/**
 * Requests a stream, using the "If-Modified-Since" header in the request so that the object will only be returned if
 * it was modified after the given time.  Otherwise, the stream field of the returned object will be null.  This is
 * useful when results from the SOA service are being added to a cache, and we only want to retrieve the result if it
 * is newer than the version stored in the cache.
 *
 * @param target       the request to send the REST service
 * @param lastModified the object will be returned iff the SOA server indicates that it was modified after this
 *                     timestamp// w  w w  .  j  a va  2  s .  c om
 * @return a timestamped stream, or a null stream with non-null timestamp
 * @throws IOException
 */
private TimestampedResponse requestIfModifiedSince(HttpUriRequest target, Calendar lastModified)
        throws IOException {
    Preconditions.checkNotNull(lastModified);
    CloseableHttpResponse response = null;
    boolean returningStream = false;
    try {
        target.addHeader(HttpHeaders.IF_MODIFIED_SINCE, HttpDateUtil.format(lastModified));
        response = remoteService.getResponse(target);
        Header[] lastModifiedHeaders = response.getHeaders(HttpHeaders.LAST_MODIFIED);
        if (lastModifiedHeaders.length == 0) {
            TimestampedResponse timestamped = new TimestampedResponse(null, response);
            returningStream = true;
            return timestamped;
        }
        if (lastModifiedHeaders.length != 1) {
            throw new RuntimeException("Expecting 1 Last-Modified header, got " + lastModifiedHeaders.length);
        }
        Calendar resultLastModified = HttpDateUtil.parse(lastModifiedHeaders[0].getValue());

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.OK.value()) {
            TimestampedResponse timestamped = new TimestampedResponse(resultLastModified, response);
            returningStream = true;
            return timestamped;
        } else if (statusCode == HttpStatus.NOT_MODIFIED.value()) {
            return new TimestampedResponse(resultLastModified, null);
        } else {
            throw new RuntimeException("Unexpected status code " + statusCode);
        }
    } finally {
        if (!returningStream && response != null) {
            response.close();
        }
    }
}

From source file:com.revo.deployr.client.call.AbstractCall.java

protected RCoreResult makeRequest(HttpUriRequest httpUriRequest, String API) {

    this.httpUriRequest = httpUriRequest;

    RCoreResultImpl pResult = null;/*  w w w . j av a  2  s .c  o  m*/

    try {
        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpUriRequest.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(this.httpUriRequest);
        StatusLine statusLine = response.getStatusLine();

        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);
        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());
    } catch (UnsupportedEncodingException ueex) {
        log.warn("AbstractCall: makeRequest unsupported encoding exception=" + ueex);
    } catch (IOException ioex) {
        log.warn("AbstractCall: makeRequest io exception=" + ioex);
    } catch (Exception ex) {
        log.warn("AbstractCall: makeRequest exception=" + ex);
    } finally {
        log.debug("AbstractCall: makeRequest pResult=" + pResult);
    }

    return pResult;
}

From source file:org.openhim.mediator.engine.connectors.HTTPConnector.java

private void copyHeaders(MediatorHTTPRequest src, HttpUriRequest dst) {
    if (src.getHeaders() != null) {
        Iterator<String> iter = src.getHeaders().keySet().iterator();
        while (iter.hasNext()) {
            String header = iter.next();
            dst.addHeader(header, src.getHeaders().get(header));
        }/*from w w  w.ja  va2 s . c o  m*/
    }
}

From source file:com.messagemedia.restapi.client.v1.internal.RestClient.java

private HttpUriRequest addHeaders(HttpUriRequest httpRequest) {
    Context context = contextThreadLocal.get(); // make sure it does not change during the execution
    if (context == null) {
        return httpRequest;
    } else {//w  w w.j  av a 2s.  com
        String account = context.getAccount();

        if (account != null && !account.isEmpty()) {
            httpRequest.addHeader("Account", account);
        }

        String username = context.getUsername();
        if (username != null && !username.isEmpty()) {
            httpRequest.addHeader("Username", username);
        }

        return httpRequest;
    }
}

From source file:ch.cyberduck.core.dropbox.client.AbstractHttpDropboxClient.java

/**
 * Get a file from the content server, returning the raw Apache HTTP Components response object
 * so you can stream it or work with it how you need.
 * You *must* call .getEntity().consumeContent() on the returned HttpResponse object or you might leak
 * connections.//from w w w . j  a v a  2  s .co m
 *
 * @param path
 * @param etag Version of the file
 * @return
 * @throws IOException
 */
protected HttpResponse getFile(String path, String etag) throws IOException {
    HttpUriRequest req = this.buildRequest(HttpGet.METHOD_NAME, "/files/" + ROOT + path, true);
    if (StringUtils.isNotBlank(etag)) {
        req.addHeader("If-None-Match", etag);
    }
    return this.request(req);
}

From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1.java

public HttpUriRequest getUpdateMetadataRequest(String song, String artist, String album) {
    if (!started) {
        return null;
    }//from   w  w w  .  j a  v  a 2s  .com

    String metadata = metadataTemplate.replace("_song_", song).replace("_artist_", artist).replace("_album_",
            album);

    final MetaDataHttpRequestParams params = new MetaDataHttpRequestParams();
    params.put("mode", "updinfo");
    params.put("charset", "UTF-8");
    params.put("song", metadata);
    params.put("pass", password);

    final HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("User-Agent", USER_AGENT);

    HttpUriRequest httpRequest = new HttpGet(MetaDataHttpRequestParams
            .getUrlWithQueryString("http://" + host + ":" + Integer.toString(port) + "/admin.cgi", params));
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpRequest.addHeader(entry.getKey(), entry.getValue());
        }
    }

    return httpRequest;
}

From source file:com.jobaline.uiautomation.framework.selenium.phantomJsThreeHourTimeoutFix.HttpCommandExecutor.java

private void setAcceptHeader(HttpUriRequest httpMethod) {
    httpMethod.addHeader("Accept", "application/json, image/png");
}

From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java

/**
 * GET?????./*from   w w w .  java 2  s .co  m*/
 * @param url ?URL
 * @param accept 
 * @return 
 */
protected final HttpUriRequest makeGetRequest(final String url, final String accept) {
    HttpUriRequest request = new HttpGet(url);
    makeCommonHeaders(request, null, accept, null);
    request.addHeader("Accept-Encoding", "gzip");
    return request;
}