Example usage for org.apache.http.client.methods HttpRequestBase setHeader

List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader

Introduction

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

Prototype

public void setHeader(String str, String str2) 

Source Link

Usage

From source file:guru.nidi.atlassian.remote.HttpUtils.java

public static void setAuthHeader(HttpRequestBase req, String username, String password) {
    req.setHeader("Authorization", "Basic "
            + Base64.encodeBase64String((username + ":" + password).getBytes(Charset.forName("utf-8"))));
}

From source file:com.normalexception.app.rx8club.httpclient.ClientUtils.java

/**
 * A set of common headers to set for our post and get
 * request bases// w  ww  . j  a v  a2  s. com
 * @param   hrb      The request base to setup
 * @return         The request base with the headers applied
 */
private static HttpRequestBase getCommonHeaders(HttpRequestBase hrb) {
    hrb.setHeader("Host", "www.rx8club.com");
    hrb.setHeader("User-Agent", WebUrls.USER_AGENT);
    hrb.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    hrb.setHeader("Accept-Encoding", "gzip,deflate,sdch");
    hrb.setHeader("Accept-Language", "en-US,en;q=0.8");
    hrb.setHeader("Cookie", LoginFactory.getInstance().getCookies());
    hrb.setHeader("Connection", "keep-alive");
    return hrb;
}

From source file:org.neo4j.ogm.drivers.http.request.HttpAuthorization.java

/**
 * Sets the authorisation header on the request, if credentials are present.
 * This code is backwards-compatible with versions of Neo4j prior to 2.2
 * that do not require users to be authenticated in order to connect.
 * In 2.2.0 M04 Neo4j only has support for single-user String-based authentication
 * based on username and password. As the security of Neo4j improves, it is
 * likely that other auth mechanisms will be enabled (e.g OAuth). When this
 * happens, we'll most likely need a proper AuthenticationManager object,
 * but for now, this will do.//from  w  w w .j  a v a2  s  . co  m
 *
 * @param request     The HttpRequest that may need an auth header.
 * @param credentials the {@link Credentials} with which to authorise the session
 */
public static void authorize(HttpRequestBase request, Credentials credentials) {
    if (credentials != null) {
        request.setHeader("Authorization", "Basic " + credentials.credentials());
    }
}

From source file:org.apache.marmotta.platform.core.util.http.HttpRequestUtil.java

/**
 * Set the <code>Cache-Control</code>-header for the provided request.
 * //  w  ww .java 2  s. c o m
 * @param request the request to modify
 * @param cacheControl the cache-control directive
 * 
 * @see HeaderConstants#CACHE_CONTROL_NO_CACHE
 * @see HeaderConstants#CACHE_CONTROL_NO_STORE
 * @see HeaderConstants#CACHE_CONTROL_MAX_AGE
 * @see HeaderConstants#CACHE_CONTROL_MAX_STALE
 * @see HeaderConstants#CACHE_CONTROL_MUST_REVALIDATE
 * @see <a
 *      href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9">RFC2616#Cache-Control</a>
 * 
 */
public static void setCacheControl(HttpRequestBase request, String cacheControl) {
    if (cacheControl != null) {
        request.setHeader(HttpHeaders.CACHE_CONTROL, cacheControl);
    } else {
        request.removeHeaders(HttpHeaders.CACHE_CONTROL);
    }
}

From source file:io.adventurous.android.api.ApiHttpClient.java

private static void setDeviceIdHeader(HttpRequestBase request, String deviceId) {
    if (null != deviceId) {
        request.setHeader(ApiConstants.HEADER_DEVICE_ID, deviceId);
    }/*from   w ww  . j  a va 2s . co  m*/
}

From source file:com.thoughtworks.go.util.HttpService.java

public static void setSizeHeader(HttpRequestBase method, long size) {
    method.setHeader(GO_ARTIFACT_PAYLOAD_SIZE, String.valueOf(size));
}

From source file:CB_Core.GCVote.GCVote.java

private static String Execute(HttpRequestBase httprequest) throws IOException, ClientProtocolException {
    httprequest.setHeader("Content-type", "application/x-www-form-urlencoded");
    // httprequest.setHeader("UserAgent", "cachebox");

    int conectionTimeout = CB_Core_Settings.conection_timeout.getValue();
    int socketTimeout = CB_Core_Settings.socket_timeout.getValue();

    // Execute HTTP Post Request
    String result = "";

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.

    HttpConnectionParams.setConnectionTimeout(httpParameters, conectionTimeout);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.

    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    HttpResponse response = httpClient.execute(httprequest);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        result += line + "\n";
    }// w  ww .  ja v a 2 s  . c om
    return result;

}

From source file:org.sonatype.nexus.testsuite.security.SimpleSessionCookieIT.java

private static HttpRequestBase withCommonBrowserHeaders(HttpRequestBase req) {
    req.setHeader(USER_AGENT, TYPICAL_BROWSER_USER_AGENT);
    req.setHeader("X-Nexus-UI", "true");
    req.setHeader(X_REQUESTED_WITH, "XMLHttpRequest");
    return req;/*from  w w  w.  java  2  s  .  co  m*/
}

From source file:CB_Utils.http.HttpUtils.java

/**
 * Executes a HTTP request and returns the response as a string. As a HttpRequestBase is given, a HttpGet or HttpPost be passed for
 * execution.<br>/*from  ww w.  ja  v a2  s. c om*/
 * <br>
 * Over the ICancel interface cycle is queried in 200 mSec, if the download should be canceled!<br>
 * Can be NULL
 * 
 * @param httprequest
 *            HttpRequestBase
 * @param icancel
 *            ICancel interface (maybe NULL)
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws ConnectTimeoutException
 */
public static String Execute(final HttpRequestBase httprequest, final ICancel icancel)
        throws IOException, ClientProtocolException, ConnectTimeoutException {

    httprequest.setHeader("Accept", "application/json");
    httprequest.setHeader("Content-type", "application/json");

    // Execute HTTP Post Request
    String result = "";

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.

    HttpConnectionParams.setConnectionTimeout(httpParameters, conectionTimeout);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.

    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    final AtomicBoolean ready = new AtomicBoolean(false);
    if (icancel != null) {
        Thread cancelChekThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    if (icancel.cancel())
                        httprequest.abort();
                } while (!ready.get());
            }
        });
        cancelChekThread.start();// start abort chk thread
    }
    HttpResponse response = httpClient.execute(httprequest);
    ready.set(true);// cancel abort chk thread

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        if (Plattform.used == Plattform.Server)
            line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
        result += line + "\n";
    }
    return result;
}

From source file:com.evolveum.midpoint.report.impl.ReportNodeUtils.java

public static InputStream executeOperation(String host, String fileName, String intraClusterHttpUrlPattern,
        String operation) throws CommunicationException, SecurityViolationException, ObjectNotFoundException,
        ConfigurationException, IOException {
    fileName = fileName.replaceAll("\\s", SPACE);
    InputStream inputStream = null;
    InputStream entityContent = null;
    LOGGER.trace("About to initiate connection with {}", host);
    try {/*from  w  ww.  ja  v a2 s  .  co  m*/
        if (StringUtils.isNotEmpty(intraClusterHttpUrlPattern)) {
            LOGGER.trace("The cluster uri pattern: {} ", intraClusterHttpUrlPattern);
            URI requestUri = buildURI(intraClusterHttpUrlPattern, host, fileName);
            fileName = URLDecoder.decode(fileName, ReportTypeUtil.URLENCODING);

            LOGGER.debug("Sending request to the following uri: {} ", requestUri);
            HttpRequestBase httpRequest = buildHttpRequest(operation);
            httpRequest.setURI(requestUri);
            httpRequest.setHeader("User-Agent", ReportTypeUtil.HEADER_USERAGENT);
            HttpClient client = HttpClientBuilder.create().build();
            try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpRequest)) {
                HttpEntity entity = response.getEntity();
                Integer statusCode = response.getStatusLine().getStatusCode();

                if (statusCode == HttpStatus.SC_OK) {
                    LOGGER.debug("Response OK, the file successfully returned by the cluster peer. ");
                    if (entity != null) {
                        entityContent = entity.getContent();
                        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = entityContent.read(buffer)) > -1) {
                            arrayOutputStream.write(buffer, 0, len);
                        }
                        arrayOutputStream.flush();
                        inputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray());
                    }
                } else if (statusCode == HttpStatus.SC_NO_CONTENT) {
                    if (HttpDelete.METHOD_NAME.equals(operation)) {
                        LOGGER.info("Deletion of the file {} was successful.", fileName);
                    }
                } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
                    LOGGER.error("The access to the report with the name {} is forbidden.", fileName);
                    String error = "The access to the report " + fileName + " is forbidden.";
                    throw new SecurityViolationException(error);
                } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
                    String error = "The report file " + fileName
                            + " was not found on the originating nodes filesystem.";
                    throw new ObjectNotFoundException(error);
                }
            } catch (ClientProtocolException e) {
                String error = "An exception with the communication protocol has occurred during a query to the cluster peer. "
                        + e.getLocalizedMessage();
                throw new CommunicationException(error);
            }
        } else {
            LOGGER.error(
                    "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly");
            throw new ConfigurationException(
                    "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly");
        }
    } catch (URISyntaxException e1) {
        throw new CommunicationException("Invalid uri syntax: " + e1.getLocalizedMessage());
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("Unhandled exception when listing nodes");
        LoggingUtils.logUnexpectedException(LOGGER, "Unhandled exception when listing nodes", e);
    } finally {
        IOUtils.closeQuietly(entityContent);
    }

    return inputStream;
}