Java Code Examples for org.apache.http.client.methods.HttpRequestBase#setHeader()

The following examples show how to use org.apache.http.client.methods.HttpRequestBase#setHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApacheHttpClient4Signer.java    From oauth1-signer-java with MIT License 6 votes vote down vote up
public void sign(HttpRequestBase req) throws IOException {
  String payload = null;
  Charset charset = Charset.defaultCharset();
  if (HttpEntityEnclosingRequestBase.class.isAssignableFrom(req.getClass())) {
    HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) req;
    HttpEntity entity = requestBase.getEntity();
    if (entity.getContentLength() > 0) {
      if (!entity.isRepeatable()) {
        throw new IOException(
            "The signer needs to read the request payload but the input stream of this request cannot be read multiple times. Please provide the payload using a separate argument or ensure that the entity is repeatable.");
      }
      ContentType contentType = ContentType.get(entity);
      charset = contentType.getCharset();
      payload = EntityUtils.toString(entity, contentType.getCharset());
    }
  }

  String authHeader = OAuth.getAuthorizationHeader(req.getURI(), req.getMethod(), payload, charset, consumerKey, signingKey);
  req.setHeader(OAuth.AUTHORIZATION_HEADER_NAME, authHeader);
}
 
Example 2
Source File: SiteToSiteRestApiClient.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void setHandshakeProperties(final HttpRequestBase httpRequest) {
    if (compress) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION, "true");
    }

    if (requestExpirationMillis > 0) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION, String.valueOf(requestExpirationMillis));
    }

    if (batchCount > 0) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_COUNT, String.valueOf(batchCount));
    }

    if (batchSize > 0) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_SIZE, String.valueOf(batchSize));
    }

    if (batchDurationMillis > 0) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_DURATION, String.valueOf(batchDurationMillis));
    }
}
 
Example 3
Source File: FileDownloader.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
private HttpResponse makeHTTPConnection() throws IOException, NullPointerException {
    if (fileURI == null) throw new NullPointerException("No file URI specified");

    HttpClient client = HttpClientBuilder.create().build();

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);

    BasicHttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(HttpClientContext.COOKIE_STORE, getWebDriverCookies(driver.manage().getCookies()));
    requestMethod.setHeader("User-Agent", getWebDriverUserAgent());

    if (null != urlParameters && (
            httpRequestMethod.equals(RequestType.PATCH) ||
                    httpRequestMethod.equals(RequestType.POST) ||
                    httpRequestMethod.equals(RequestType.PUT))
            ) {
        ((HttpEntityEnclosingRequestBase) requestMethod).setEntity(new UrlEncodedFormEntity(urlParameters));
    }

    return client.execute(requestMethod, localContext);
}
 
Example 4
Source File: HttpSolrClient.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void setBasicAuthHeader(@SuppressWarnings({"rawtypes"})SolrRequest request, HttpRequestBase method) throws UnsupportedEncodingException {
  if (request.getBasicAuthUser() != null && request.getBasicAuthPassword() != null) {
    String userPass = request.getBasicAuthUser() + ":" + request.getBasicAuthPassword();
    String encoded = Base64.byteArrayToBase64(userPass.getBytes(FALLBACK_CHARSET));
    method.setHeader(new BasicHeader("Authorization", "Basic " + encoded));
  }
}
 
Example 5
Source File: BuddycloudHTTPHelper.java    From buddycloud-android with Apache License 2.0 5 votes vote down vote up
protected static void addAuthHeader(HttpRequestBase method, Context parent) {
	String loginPref = Preferences.getPreference(parent,
			Preferences.MY_CHANNEL_JID);
	String passPref = Preferences.getPreference(parent,
			Preferences.PASSWORD);
	String auth = loginPref + ":" + passPref;
	String authToken = Base64.encodeToString(auth.getBytes(),
			Base64.NO_WRAP);
	method.setHeader("Authorization", "Basic " + authToken);
}
 
Example 6
Source File: AbstractRefTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
protected HttpResponse callUri(
    final ODataHttpMethod httpMethod, final String uri,
    final String additionalHeader, final String additionalHeaderValue,
    final String requestBody, final String requestContentType,
    final HttpStatusCodes expectedStatusCode) throws Exception {

  HttpRequestBase request =
      httpMethod == ODataHttpMethod.GET ? new HttpGet() :
          httpMethod == ODataHttpMethod.DELETE ? new HttpDelete() :
              httpMethod == ODataHttpMethod.POST ? new HttpPost() :
                  httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch();
  request.setURI(URI.create(getEndpoint() + uri));
  if (additionalHeader != null) {
    request.addHeader(additionalHeader, additionalHeaderValue);
  }
  if (requestBody != null) {
    ((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody));
    request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType);
  }

  final HttpResponse response = getHttpClient().execute(request);

  assertNotNull(response);
  assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode());

  if (expectedStatusCode == HttpStatusCodes.OK) {
    assertNotNull(response.getEntity());
    assertNotNull(response.getEntity().getContent());
  } else if (expectedStatusCode == HttpStatusCodes.CREATED) {
    assertNotNull(response.getEntity());
    assertNotNull(response.getEntity().getContent());
    assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION));
  } else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) {
    assertTrue(response.getEntity() == null || response.getEntity().getContent() == null);
  }

  return response;
}
 
Example 7
Source File: RemoteSystemClient.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
protected static void setHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
  httpRequest.setHeader("User-Agent", "GH::watch");
  if (headers != null) {
    for (Entry<String, String> he : headers.entrySet()) {
      Log.d(TAG, "Set request header " + he.getKey() + ":" + he.getValue());
      httpRequest.setHeader(he.getKey(), he.getValue());
    }
  }
}
 
Example 8
Source File: HttpClientUtils.java    From train-ticket-reaper with MIT License 5 votes vote down vote up
/**
 * 设置头信息
 *
 * @param headers
 * @param httpPost
 */
private static void setHeaders(Map<String, String> headers, HttpRequestBase httpPost) {
    if (headers != null) {
        Iterator<Entry<String, String>> it = headers.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, String> entry = it.next();
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
    }
}
 
Example 9
Source File: AbstractSingleCheckThread.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private CloseableHttpResponse doRequest(final HttpRequestBase request) throws IOException {
	if (log.isDebugEnabled()) {
		log.debug(request.getMethod() + " " + request.getURI());
	}
	Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(check.getSocketTimeout()).setConnectTimeout(check.getConnectionTimeout());
	if (check.getHttpProxyServer() != null && !check.getHttpProxyServer().isEmpty()) {
		HttpHost httpProxy = new HttpHost(check.getHttpProxyServer(), check.getHttpProxyPort());
		requestConfigBuilder.setProxy(httpProxy);
	}
	RequestConfig requestConfig = requestConfigBuilder.build();
	request.setConfig(requestConfig);
       String header = check.getHeader();

       if(null!=header && header.length()>0 && header.contains(":"))
       {
           log.info("header:" + header);
           String[] headerKV = header.split(":");
           request.setHeader(headerKV[0],headerKV[1]);
       }

	CloseableHttpResponse response = null;
	try {
		request.setHeader("User-Agent", check.getUserAgent());
		response = httpClient.execute(request);
	} catch (SSLHandshakeException ex) {
		// ignore ValidatorException -> thrown when Java cannot validate
		// certificate
		log.error("java could not validate certificate for URL: " + request.getURI(), ex);
		return null;
	}
	if (log.isDebugEnabled()) {
		log.debug("status: " + response.getStatusLine());
	}
	return response;
}
 
Example 10
Source File: HttpService.java    From gocd with Apache License 2.0 5 votes vote down vote up
public CloseableHttpResponse execute(HttpRequestBase httpMethod) throws IOException {
    GoAgentServerHttpClient client = httpClientFactory.httpClient();

    httpMethod.setHeader("X-Agent-GUID", agentRegistry.uuid());
    httpMethod.setHeader("Authorization", agentRegistry.token());

    CloseableHttpResponse response = client.execute(httpMethod);
    LOGGER.info("Got back {} from server", response.getStatusLine().getStatusCode());
    return response;
}
 
Example 11
Source File: OrientNpmProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Execute http client request.
 */
protected HttpResponse execute(final Context context, final HttpClient client, final HttpRequestBase request)
    throws IOException
{
  String bearerToken = getRepository().facet(HttpClientFacet.class).getBearerToken();
  if (StringUtils.isNotBlank(bearerToken)) {
    request.setHeader("Authorization", "Bearer " + bearerToken);
  }
  return super.execute(context, client, request);
}
 
Example 12
Source File: DefaultHttpRequestProcessor.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
private void addCommonHeaders(HttpRequestBase httpMtd, Map<String, String> metadata) {
    httpMtd.setHeader(CLIENT_IP_HEADER_NAME, clientIp);
    String app = getMetricConfig().getString(LookoutConfig.APP_NAME);
    if (StringUtils.isNotEmpty(app)) {
        httpMtd.setHeader(APP_HEADER_NAME, app);
    }
    if (metadata == null) {
        return;
    }
    for (Map.Entry<String, String> entry : metadata.entrySet()) {
        httpMtd.setHeader(entry.getKey(), entry.getValue());
    }
}
 
Example 13
Source File: HttpUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 设置header 
 *  
 * @param method  method
 * @param headers  headers
 */ 
private static void setHeader(HttpRequestBase method,  Map<String, String> headers) { 
	if (null != headers) { 
		Iterator<String> keys = headers.keySet().iterator(); 
		while (keys.hasNext()) { 
			String key = keys.next(); 
			String value = headers.get(key); 
			method.setHeader(key, value); 
		} 
	} 
}
 
Example 14
Source File: BuddycloudHTTPHelper.java    From buddycloud-android with Apache License 2.0 4 votes vote down vote up
protected static void addAcceptJSONHeader(HttpRequestBase method) {
	method.setHeader("Accept", "application/json");
}
 
Example 15
Source File: RemoteSystemClient.java    From ghwatch with Apache License 2.0 4 votes vote down vote up
protected static void setJsonContentTypeHeader(HttpRequestBase request) {
  request.setHeader("Content-Type", "application/json; charset=utf-8");
}
 
Example 16
Source File: WordpressRestBackend.java    From mxisd with GNU Affero General Public License v3.0 4 votes vote down vote up
protected CloseableHttpResponse runRequest(HttpRequestBase request) throws IOException {
    request.setHeader("Authorization", "Bearer " + token);
    return client.execute(request);
}
 
Example 17
Source File: APIRequest.java    From Faceless with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void addCustomHTTPHeaders(HttpRequestBase request) {
	request.setHeader(HTTP_HEADER_API_SIGNATURE, getRequestSignature());
	request.setHeader(HTTP_HEADER_API_TIMESTAMP, mTimestamp);
}
 
Example 18
Source File: HttpQueryContext.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static void addDefineHeaders(HttpRequestBase req,String sessionId){
    req.setHeader("X-SessionId",sessionId);
    req.addHeader("Cache-Control","no-cache no-store");
    req.addHeader("Pragma","no-cache");
}
 
Example 19
Source File: ConfigServerApiImpl.java    From vespa with Apache License 2.0 4 votes vote down vote up
private void setContentTypeToApplicationJson(HttpRequestBase request) {
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
}
 
Example 20
Source File: ClientHelper.java    From ballerina-message-broker with Apache License 2.0 2 votes vote down vote up
/**
 * Set basic auth header to http request
 *
 * @param httpRequestBase http request
 * @param username        username
 * @param password        password
 */
public static void setAuthHeader(HttpRequestBase httpRequestBase, String username, String password) {
    String basicAuthHeader = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
    httpRequestBase.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), AUTH_TYPE_BASIC + basicAuthHeader);
}