Java Code Examples for org.apache.http.client.methods.RequestBuilder#addHeader()

The following examples show how to use org.apache.http.client.methods.RequestBuilder#addHeader() . 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: NomadApiClient.java    From nomad-java-sdk with Mozilla Public License 2.0 6 votes vote down vote up
private HttpUriRequest buildRequest(
        RequestBuilder requestBuilder,
        @Nullable RequestOptions options
) {
    String region =    getConfig().getRegion();
    String namespace = getConfig().getNamespace();
    String authToken = getConfig().getAuthToken();

    if (options != null) {
        if (options.getRegion() != null)
            region = options.getRegion();
        if (options.getNamespace() != null)
            namespace = options.getNamespace();
        if (options.getAuthToken() != null)
            authToken = options.getAuthToken();
    }

    if (region != null && !region.isEmpty())
        requestBuilder.addParameter("region", region);
    if (namespace != null && !namespace.isEmpty())
        requestBuilder.addParameter("namespace", namespace);
    if (authToken != null && !authToken.isEmpty())
        requestBuilder.addHeader("X-Nomad-Token", authToken);

    return requestBuilder.build();
}
 
Example 2
Source File: RfRequestBuilder.java    From restfiddle with Apache License 2.0 6 votes vote down vote up
private void setHeaders(RfRequestDTO requestDTO, RequestBuilder requestBuilder) {
List<RfHeaderDTO> headers = requestDTO.getHeaders();
if (headers != null && !headers.isEmpty()) {
    boolean contentTypeFound = false;
    for (RfHeaderDTO rfHeaderDTO : headers) {
	if (rfHeaderDTO.getHeaderName() != null && rfHeaderDTO.getHeaderValue() != null) {
	    requestBuilder.addHeader(rfHeaderDTO.getHeaderName(), rfHeaderDTO.getHeaderValue());
	}
	if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(rfHeaderDTO.getHeaderName())) {
	    contentTypeFound = true;
	}
    }
    if (!contentTypeFound) {
	requestBuilder.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    }
} else {
    requestBuilder.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
}
   }
 
Example 3
Source File: HttpClaimInformationPointProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void setHeaders(RequestBuilder builder, HttpFacade httpFacade) {
    Object headersDef = config.get("headers");

    if (headersDef != null) {
        Map<String, Object> headers = Map.class.cast(headersDef);

        for (Entry<String, Object> header : headers.entrySet()) {
            Object value = header.getValue();
            List<String> headerValues = new ArrayList<>();

            if (value instanceof Collection) {
                Collection values = Collection.class.cast(value);

                for (Object item : values) {
                    headerValues.addAll(PlaceHolders.resolve(item.toString(), httpFacade));
                }
            } else {
                headerValues.addAll(PlaceHolders.resolve(value.toString(), httpFacade));
            }

            for (String headerValue : headerValues) {
                builder.addHeader(header.getKey(), headerValue);
            }
        }
    }
}
 
Example 4
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void setheaders(RequestBuilder rb, Map<String, String> headers) {
  // Add any defined headers
  if (headers.size() > 0) {
    for (HashMap.Entry<String, String> entry : headers.entrySet()) {
      rb.addHeader(entry.getKey(), entry.getValue());
    }
  }
}
 
Example 5
Source File: RDF4JProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected HttpUriRequest getQueryMethod(QueryLanguage ql, String query, String baseURI, Dataset dataset,
		boolean includeInferred, int maxQueryTime, Binding... bindings) {
	RequestBuilder builder = null;
	String transactionURL = getTransactionURL();
	if (transactionURL != null) {
		builder = RequestBuilder.put(transactionURL);
		builder.setHeader("Content-Type", Protocol.SPARQL_QUERY_MIME_TYPE + "; charset=utf-8");
		builder.addParameter(Protocol.ACTION_PARAM_NAME, Action.QUERY.toString());
		for (NameValuePair nvp : getQueryMethodParameters(ql, null, baseURI, dataset, includeInferred, maxQueryTime,
				bindings)) {
			builder.addParameter(nvp);
		}
		// in a PUT request, we carry the actual query string as the entity
		// body rather than a parameter.
		builder.setEntity(new StringEntity(query, UTF8));
		pingTransaction();
	} else {
		builder = RequestBuilder.post(getQueryURL());
		builder.setHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8");

		builder.setEntity(new UrlEncodedFormEntity(
				getQueryMethodParameters(ql, query, baseURI, dataset, includeInferred, maxQueryTime, bindings),
				UTF8));
	}
	// functionality to provide custom http headers as required by the
	// applications
	for (Map.Entry<String, String> additionalHeader : getAdditionalHttpHeaders().entrySet()) {
		builder.addHeader(additionalHeader.getKey(), additionalHeader.getValue());
	}
	return builder.build();
}
 
Example 6
Source File: RDF4JProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected HttpUriRequest getUpdateMethod(QueryLanguage ql, String update, String baseURI, Dataset dataset,
		boolean includeInferred, int maxExecutionTime, Binding... bindings) {
	RequestBuilder builder = null;
	String transactionURL = getTransactionURL();
	if (transactionURL != null) {
		builder = RequestBuilder.put(transactionURL);
		builder.addHeader("Content-Type", Protocol.SPARQL_UPDATE_MIME_TYPE + "; charset=utf-8");
		builder.addParameter(Protocol.ACTION_PARAM_NAME, Action.UPDATE.toString());
		for (NameValuePair nvp : getUpdateMethodParameters(ql, null, baseURI, dataset, includeInferred,
				maxExecutionTime, bindings)) {
			builder.addParameter(nvp);
		}
		// in a PUT request, we carry the only actual update string as the
		// request body - the rest is sent as request parameters
		builder.setEntity(new StringEntity(update, UTF8));
		pingTransaction();
	} else {
		builder = RequestBuilder.post(getUpdateURL());
		builder.addHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8");

		builder.setEntity(new UrlEncodedFormEntity(getUpdateMethodParameters(ql, update, baseURI, dataset,
				includeInferred, maxExecutionTime, bindings), UTF8));
	}
	// functionality to provide custom http headers as required by the
	// applications
	for (Map.Entry<String, String> additionalHeader : getAdditionalHttpHeaders().entrySet()) {
		builder.addHeader(additionalHeader.getKey(), additionalHeader.getValue());
	}
	return builder.build();
}
 
Example 7
Source File: HeaderUtils.java    From zerocode with Apache License 2.0 5 votes vote down vote up
public static void processFrameworkDefault(Map<String, Object> headers, RequestBuilder requestBuilder) {
    if (headers != null) {
        Map headersMap = headers;
        for (Object key : headersMap.keySet()) {
            if(CONTENT_TYPE.equalsIgnoreCase((String)key) && MULTIPART_FORM_DATA.equals(headersMap.get(key))){
                continue;
            }
            removeDuplicateHeaders(requestBuilder, (String) key);
            requestBuilder.addHeader((String) key, (String) headersMap.get(key));
            LOGGER.info("Overridden the header key:{}, with value:{}", key, headersMap.get(key));
        }
    }
}
 
Example 8
Source File: BasicHttpClient.java    From zerocode with Apache License 2.0 5 votes vote down vote up
private void addCookieToHeader(RequestBuilder uploadRequestBuilder) {
    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    // Setting cookies:
    // Highly discouraged to use sessions, but in case of any server dependent upon session,
    // then it is taken care here.
    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
    if (COOKIE_JSESSIONID_VALUE != null) {
        uploadRequestBuilder.addHeader("Cookie", (String) COOKIE_JSESSIONID_VALUE);
    }
}
 
Example 9
Source File: ApiBase.java    From nomad-java-sdk with Mozilla Public License 2.0 5 votes vote down vote up
private RequestBuilder prepareWrite(
        final RequestBuilder builder,
        final URIBuilder uri,
        @Nullable final WriteOptions options
) {
    String region = apiClient.getConfig().getRegion();
    String namespace = apiClient.getConfig().getNamespace();
    String secretId = apiClient.getConfig().getAuthToken();

    if (options != null) {
        if (options.getRegion() != null)
            region = options.getRegion();
        if (options.getNamespace() != null)
            namespace = options.getNamespace();
        if (options.getSecretId() != null)
            secretId = options.getSecretId();
    }

    if (region != null)
        uri.addParameter("region", region);
    if (namespace != null)
        uri.addParameter("namespace", namespace);
    if (secretId != null)
        builder.addHeader("X-Nomad-Token", secretId);

    return builder.setUri(build(uri));
}
 
Example 10
Source File: MixerHttpClient.java    From beam-client-java with MIT License 5 votes vote down vote up
/**
 * Creates a {@link org.apache.http.HttpRequest} given a type, path, and optional content.
 *
 * @param requestType The type of HTTP/1.1 request to make (see {@link RequestType}
 *                    for more details.
 * @param uri The URI to request content from.
 * @param args The content of the request.  This parameter is optional and considered to be nullable.
 *
 * @return A request built from the specification above.
 */
private HttpUriRequest makeRequest(RequestType requestType, URI uri, Object... args) {
    RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT);
    config.setCookieSpec(CookieSpecs.BEST_MATCH);

    RequestBuilder requestBuilder = RequestBuilder.create(requestType.name())
                         .setUri(uri)
                         .setConfig(config.build())
                         .setEntity(this.makeEntity(args))
                         .setHeader("User-Agent", this.getUserAgent());

    if (this.oauthToken != null) {
        requestBuilder.addHeader("Authorization", "Bearer " + this.oauthToken);
    }
    if (this.jwt != null) {
        requestBuilder.addHeader("Authorization", "JWT " + this.jwtString);
    }

    if (this.oauthToken == null && this.jwt == null) {
        requestBuilder.addHeader("Client-Id", clientId);
    }
    if (this.csrfToken != null) {
        requestBuilder.addHeader(CSRF_TOKEN_HEADER, this.csrfToken);
    }

    return requestBuilder.build();
}
 
Example 11
Source File: BasicAuthHandler.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
public void setBasicAuthWithBase64Encode(RfRequestDTO requestDTO, RequestBuilder requestBuilder) {
BasicAuthDTO basicAuthDTO = requestDTO.getBasicAuthDTO();
if (basicAuthDTO == null) {
    return;
}
String userName = basicAuthDTO.getUsername();
String password = basicAuthDTO.getPassword();
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
    return;
}

String authStr = userName + ":" + password;
String encodedAuth = (new BASE64Encoder()).encode(authStr.getBytes());
requestBuilder.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);
   }
 
Example 12
Source File: PostGenerator.java    From tomcat-mongo-access-log with Apache License 2.0 5 votes vote down vote up
public static HttpUriRequest gen(int port) throws URISyntaxException {
  String uri = "http://localhost:" + port + uris[r.nextInt(uris.length)];
  RequestBuilder rb = RequestBuilder.post().setUri(new URI(uri));
  for(int j = 0; j < r.nextInt(paramNames.length); j++) {
    rb.addParameter(
        paramNames[r.nextInt(paramNames.length)], 
        paramValues[r.nextInt(paramValues.length)]
    );
  }
  rb.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  return rb.build();
}
 
Example 13
Source File: FileUploadDownloadClient.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private static void addHeadersAndParameters(RequestBuilder requestBuilder, @Nullable List<Header> headers,
    @Nullable List<NameValuePair> parameters) {
  if (headers != null) {
    for (Header header : headers) {
      requestBuilder.addHeader(header);
    }
  }
  if (parameters != null) {
    for (NameValuePair parameter : parameters) {
      requestBuilder.addParameter(parameter);
    }
  }
}
 
Example 14
Source File: HttpUriRequestConverter.java    From webmagic with Apache License 2.0 5 votes vote down vote up
private HttpUriRequest convertHttpUriRequest(Request request, Site site, Proxy proxy) {
    RequestBuilder requestBuilder = selectRequestMethod(request).setUri(UrlUtils.fixIllegalCharacterInUrl(request.getUrl()));
    if (site.getHeaders() != null) {
        for (Map.Entry<String, String> headerEntry : site.getHeaders().entrySet()) {
            requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    if (site != null) {
        requestConfigBuilder.setConnectionRequestTimeout(site.getTimeOut())
                .setSocketTimeout(site.getTimeOut())
                .setConnectTimeout(site.getTimeOut())
                .setCookieSpec(CookieSpecs.STANDARD);
    }

    if (proxy != null) {
        requestConfigBuilder.setProxy(new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme()));
    }
    requestBuilder.setConfig(requestConfigBuilder.build());
    HttpUriRequest httpUriRequest = requestBuilder.build();
    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
        for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
            httpUriRequest.addHeader(header.getKey(), header.getValue());
        }
    }
    return httpUriRequest;
}