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

The following examples show how to use org.apache.http.client.methods.RequestBuilder#addParameter() . 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: HttpClientDelegate.java    From wechat-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 构造HttpUriRequest请求.
 *
 * @param method 请求方法
 * @param url    请求地址
 * @param params 请求(key,value)数据
 * @param data   请求体文本数据
 * @param file   请求体二进制文件
 */
private static HttpUriRequest buildRequest(String method, String url, Map<String, String> params,
                                           String data, File file) {
    RequestBuilder builder = RequestBuilder.create(method).setUri(url);
    if (params != null) {
        for (String key : params.keySet()) {
            builder.addParameter(new BasicNameValuePair(key, params.get(key)));
        }
    }
    if (data != null) {
        builder.setEntity(new StringEntity(data, Const.Charset.UTF_8));
    }
    if (file != null) {
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("media", file);
        builder.setEntity(entityBuilder.build());
    }
    return builder.build();
}
 
Example 2
Source File: ApiBase.java    From nomad-java-sdk with Mozilla Public License 2.0 6 votes vote down vote up
private <T> ServerQueryResponse<T> executeServerQueryRaw(
        @Nullable final QueryOptions<T> options,
        @Nullable final String wait,
        final ValueExtractor<T> valueExtractor,
        RequestBuilder requestBuilder
) throws IOException, NomadException {
    if (options != null) {
        if (options.getIndex() != null)
            requestBuilder.addParameter("index", options.getIndex().toString());
        if (wait != null)
            requestBuilder.addParameter("wait", wait);
        if (options.isAllowStale())
            requestBuilder.addParameter("stale", null);
    }
    return apiClient.execute(requestBuilder, new ServerQueryResponseAdapter<>(valueExtractor), options);
}
 
Example 3
Source File: OperatorApi.java    From nomad-java-sdk with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Updates the autopilot configuration.
 *
 * @param autopilotConfiguration the desired autopilot configuration
 * @param options options controlling how the request is performed
 * @param cas if not null, use check-and-set semantics on the update
 * @throws IOException    if there is an HTTP or lower-level problem
 * @throws NomadException if the response signals an error or cannot be deserialized
 * @see <a href="https://www.nomadproject.io/api/operator.html#update-autopilot-configuration">{@code PUT /v1/operator/autopilot/configuration}</a>
 */
public NomadResponse<Boolean> updateAutopilotConfiguration(
        AutopilotConfiguration autopilotConfiguration,
        @Nullable WriteOptions options,
        @Nullable BigInteger cas
    ) throws IOException, NomadException {
    RequestBuilder builder = put(
            uri("/v1/operator/autopilot/configuration"),
            autopilotConfiguration,
            options
    );
    if (cas != null) {
        builder.addParameter("cas", cas.toString());
    }
    return executeServerAction(
            builder,
            NomadJson.parserFor(Boolean.class)
    );
}
 
Example 4
Source File: OperatorApi.java    From nomad-java-sdk with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Updates the scheduler configuration.
 *
 * @param schedulerConfiguration the desired scheduler configuration
 * @param options options controlling how the request is performed
 * @param cas if not null, use check-and-set semantics on the update
 * @throws IOException    if there is an HTTP or lower-level problem
 * @throws NomadException if the response signals an error or cannot be deserialized
 * @see <a href="https://www.nomadproject.io/api/operator.html#update-scheduler-configuration">{@code PUT /v1/operator/scheduler/configuration}</a>
 */
public NomadResponse<SchedulerSetConfigurationResponse> updateSchedulerConfiguration(
        SchedulerConfiguration schedulerConfiguration,
        @Nullable WriteOptions options,
        @Nullable BigInteger cas
) throws IOException, NomadException {
    RequestBuilder builder = put(
            uri("/v1/operator/scheduler/configuration"),
            schedulerConfiguration,
            options
    );
    if (cas != null) {
        builder.addParameter("cas", cas.toString());
    }
    return executeServerAction(
            builder,
            NomadJson.parserFor(SchedulerSetConfigurationResponse.class)
    );
}
 
Example 5
Source File: HttpClaimInformationPointProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void setParameters(RequestBuilder builder, HttpFacade httpFacade) {
    Object config = this.config.get("parameters");

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

        for (Entry<String, Object> paramDef : paramsDef.entrySet()) {
            Object value = paramDef.getValue();
            List<String> paramValues = new ArrayList<>();

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

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

            for (String paramValue : paramValues) {
                builder.addParameter(paramDef.getKey(), paramValue);
            }
        }
    }
}
 
Example 6
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 7
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 8
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 9
Source File: SimpleWebhookRunner.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private HttpUriRequest addGetParams(RequestBuilder requestBuilder, String login, String email, String name, String subject, String content) {
    requestBuilder.addParameter("login", login);
    requestBuilder.addParameter("email", email);
    requestBuilder.addParameter("name", name);
    requestBuilder.addParameter("subject", subject);
    requestBuilder.addParameter("content", content);
    return requestBuilder.build();
}
 
Example 10
Source File: HttpUriRequestBuilder.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public HttpUriRequest build() {
    validate();
    final RequestBuilder builder = RequestBuilder.create(method.toString()).setUri(buildUri());
    if (!methodParameters.isEmpty()) {
        for (final Entry<String, String> entry : methodParameters.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue());
        }
    }
    if (jsonPayload.isPresent()) {
        builder.addHeader(new BasicHeader(CONTENT_TYPE, JSON_CONTENT_TYPE))
               .setEntity(new StringEntity(jsonPayload.get(), ContentType.create(JSON_CONTENT_TYPE, Consts.UTF_8)));
    }
    return builder.build();
}
 
Example 11
Source File: DefaultZtsClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
private ZToken getRoleToken(AthenzDomain domain, String roleName) {
    URI uri = ztsUrl.resolve(String.format("domain/%s/token", domain.getName()));
    RequestBuilder requestBuilder = RequestBuilder.get(uri)
            .addHeader("Content-Type", "application/json");
    if (roleName != null) {
        requestBuilder.addParameter("role", roleName);
    }
    HttpUriRequest request = requestBuilder.build();
    return execute(request, response -> {
        RoleTokenResponseEntity roleTokenResponseEntity = readEntity(response, RoleTokenResponseEntity.class);
        return roleTokenResponseEntity.token;
    });
}
 
Example 12
Source File: HttpMethod.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void preExecute(RequestBuilder builder) {
    for (Map.Entry<String, List<String>> param : params.entrySet()) {
        for (String value : param.getValue()) {
            builder.addParameter(param.getKey(), value);
        }
    }
}
 
Example 13
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 14
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 15
Source File: HttpUriRequestBuilder.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public HttpUriRequest build() {
    validate();
    final RequestBuilder builder = RequestBuilder.create(method.toString()).setUri(buildUri());
    if (!methodParameters.isEmpty()) {
        for (final Entry<String, String> entry : methodParameters.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue());
        }
    }
    if (jsonPayload.isPresent()) {
        builder.addHeader(new BasicHeader(CONTENT_TYPE, JSON_CONTENT_TYPE))
            .setEntity(new StringEntity(jsonPayload.get(), ContentType.create(JSON_CONTENT_TYPE, Consts.UTF_8)));
    }
    return builder.build();
}
 
Example 16
Source File: RemoteHttpCacheDispatcher.java    From commons-jcs with Apache License 2.0 4 votes vote down vote up
/**
 * Process single request
 *
 * @param requestAsByteArray request body
 * @param remoteCacheRequest the cache request
 * @param url target url
 *
 * @return byte[] - the response
 *
 * @throws IOException
 * @throws HttpException
 */
protected <K, V> byte[] processRequest( byte[] requestAsByteArray,
        RemoteCacheRequest<K, V> remoteCacheRequest, String url )
    throws IOException, HttpException
{
    RequestBuilder builder = RequestBuilder.post( url ).setCharset( DEFAULT_ENCODING );

    if ( getRemoteHttpCacheAttributes().isIncludeCacheNameAsParameter()
        && remoteCacheRequest.getCacheName() != null )
    {
        builder.addParameter( PARAMETER_CACHE_NAME, remoteCacheRequest.getCacheName() );
    }
    if ( getRemoteHttpCacheAttributes().isIncludeKeysAndPatternsAsParameter() )
    {
        String keyValue = "";
        switch ( remoteCacheRequest.getRequestType() )
        {
            case GET:
            case REMOVE:
            case GET_KEYSET:
                keyValue = remoteCacheRequest.getKey().toString();
                break;
            case GET_MATCHING:
                keyValue = remoteCacheRequest.getPattern();
                break;
            case GET_MULTIPLE:
                keyValue = remoteCacheRequest.getKeySet().toString();
                break;
            case UPDATE:
                keyValue = remoteCacheRequest.getCacheElement().getKey().toString();
                break;
            default:
                break;
        }
        builder.addParameter( PARAMETER_KEY, keyValue );
    }
    if ( getRemoteHttpCacheAttributes().isIncludeRequestTypeasAsParameter() )
    {
        builder.addParameter( PARAMETER_REQUEST_TYPE,
            remoteCacheRequest.getRequestType().toString() );
    }

    builder.setEntity(new ByteArrayEntity( requestAsByteArray ));
    HttpResponse httpResponse = doWebserviceCall( builder );
    byte[] response = EntityUtils.toByteArray( httpResponse.getEntity() );
    return response;
}
 
Example 17
Source File: HttpMethod.java    From nexus3-keycloak-plugin with Apache License 2.0 4 votes vote down vote up
protected void preExecute(RequestBuilder builder) {
    for (Map.Entry<String, String> param : this.params.entrySet()) {
        builder.addParameter(param.getKey(), param.getValue());
    }
}
 
Example 18
Source File: StatusApi.java    From nomad-java-sdk with Mozilla Public License 2.0 3 votes vote down vote up
/**
 * List the addresses of the Raft peers in the given or active region.
 *
 * @param region the region to forward the request to
 * @throws IOException    if there is an HTTP or lower-level problem
 * @throws NomadException if the response signals an error or cannot be deserialized
 * @see <a href="https://www.nomadproject.io/docs/http/status.html">{@code GET /v1/status/peers}</a>
 */
public NomadResponse<List<String>> peers(@Nullable String region) throws IOException, NomadException {
    RequestBuilder request = get("/v1/status/peers");
    if (region != null)
        request.addParameter("region", region);
    return executePlain(request, NomadJson.parserForListOf(String.class));
}
 
Example 19
Source File: StatusApi.java    From nomad-java-sdk with Mozilla Public License 2.0 3 votes vote down vote up
/**
 * Queries the address of the Raft leader in the given or active region.
 *
 * @param region the region to forward the request to
 * @throws IOException    if there is an HTTP or lower-level problem
 * @throws NomadException if the response signals an error or cannot be deserialized
 * @see <a href="https://www.nomadproject.io/docs/http/status.html">{@code GET /v1/status/peers}</a>
 */
public NomadResponse<String> leader(@Nullable String region) throws IOException, NomadException {
    final RequestBuilder request = get("/v1/status/leader");
    if (region != null)
        request.addParameter("region", region);
    return executePlain(request, NomadJson.parserFor(String.class));
}