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

The following examples show how to use org.apache.http.client.methods.RequestBuilder#build() . 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: AsyncInternalClient.java    From fc-java-sdk with MIT License 6 votes vote down vote up
protected <Res> void asyncSend(HttpRequest request, AbstractResponseConsumer<Res> consumer, FutureCallback<Res> callback,
                               String contentType, HttpMethod method, boolean httpInvoke)
        throws ClientException {
    try{
        // try refresh credentials if CredentialProvider set
        config.refreshCredentials();

        // Add all needed headers
        if (!httpInvoke
                || !ANONYMOUS.equals(((HttpInvokeFunctionRequest) request).getAuthType())) {
            FcUtil.signRequest(config, request, contentType, method, httpInvoke);
        }

        // Construct HttpRequest
        PrepareUrl prepareUrl = FcUtil.prepareUrl(request.getPath(), request.getQueryParams(), this.config);
        RequestBuilder requestBuilder = RequestBuilder.create(method.name())
                .setUri(prepareUrl.getUrl());
        copyToRequest(request, requestBuilder);
        HttpUriRequest httpRequest = requestBuilder.build();

        HttpHost httpHost = URIUtils.extractHost(httpRequest.getURI());
        httpClient.execute(new FcRequestProducer(httpHost, httpRequest), consumer, callback);
    } catch (Exception e) {
        throw new ClientException(e);
    }
}
 
Example 3
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 4
Source File: DefaultZtsClient.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Override
public AwsTemporaryCredentials getAwsTemporaryCredentials(AthenzDomain athenzDomain, AwsRole awsRole, Duration duration, String externalId) {
    URI uri = ztsUrl.resolve(
            String.format("domain/%s/role/%s/creds", athenzDomain.getName(), awsRole.encodedName()));
    RequestBuilder requestBuilder = RequestBuilder.get(uri);

    // Add optional durationSeconds and externalId parameters
    Optional.ofNullable(duration).ifPresent(d -> requestBuilder.addParameter("durationSeconds", Long.toString(duration.getSeconds())));
    Optional.ofNullable(externalId).ifPresent(s -> requestBuilder.addParameter("externalId", s));

    HttpUriRequest request = requestBuilder.build();
    return execute(request, response -> {
        AwsTemporaryCredentialsResponseEntity entity = readEntity(response, AwsTemporaryCredentialsResponseEntity.class);
        return entity.credentials();
    });
}
 
Example 5
Source File: GitHubAPICaller.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private HttpUriRequest buildRequest(String url, String etag) {
  RequestBuilder requestBuilder =
      RequestBuilder.get(url).setHeader(AUTHORIZATION_HEADER, TOKEN_PREFIX + _personalAccessToken);
  if (etag != null) {
    requestBuilder.setHeader(IF_NONE_MATCH_HEADER, etag);
  }
  setTimeout(requestBuilder);
  return requestBuilder.build();
}
 
Example 6
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 7
Source File: FileUploadDownloadClient.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private static HttpUriRequest getDeleteFileRequest(String method, URI uri, ContentBody contentBody,
    @Nullable List<Header> headers, @Nullable List<NameValuePair> parameters, int socketTimeoutMs) {
  // Build the Http entity
  HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
      .addPart(contentBody.getFilename(), contentBody).build();

  // Build the request
  RequestBuilder requestBuilder =
      RequestBuilder.create(method).setVersion(HttpVersion.HTTP_1_1).setUri(uri).setEntity(entity);
  addHeadersAndParameters(requestBuilder, headers, parameters);
  setTimeout(requestBuilder, socketTimeoutMs);
  return requestBuilder.build();
}
 
Example 8
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;
}
 
Example 9
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 10
Source File: AbstractHttpClient.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
/**
 * Execute the web service call
 * <p>
 * @param builder builder for the post request
 *
 * @return the call response
 *
 * @throws IOException on i/o error
 */
protected final HttpResponse doWebserviceCall( RequestBuilder builder )
    throws IOException
{
    preProcessWebserviceCall( builder.setVersion(httpVersion) );
    HttpUriRequest request = builder.build();
    HttpResponse httpResponse = this.httpClient.execute( request );
    postProcessWebserviceCall( request, httpResponse );

    return httpResponse;
}
 
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: 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 13
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 14
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 15
Source File: OAuthRefreshTokenProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
HttpUriRequest createHttpRequest() {
    final RequestBuilder builder = RequestBuilder.post(authorizationEndpoint);

    if (authorizeUsingParameters) {
        builder.addParameter("client_id", state.getClientId())
            .addParameter("client_secret", state.getClientSecret());
    }

    builder.addParameter("refresh_token", state.getRefreshToken())
        .addParameter("grant_type", "refresh_token");

    return builder.build();
}
 
Example 16
Source File: FileUploadDownloadClient.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
private static HttpUriRequest getDownloadFileRequest(URI uri, int socketTimeoutMs) {
  RequestBuilder requestBuilder = RequestBuilder.get(uri).setVersion(HttpVersion.HTTP_1_1);
  setTimeout(requestBuilder, socketTimeoutMs);
  return requestBuilder.build();
}
 
Example 17
Source File: HTTPUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Execute a request via HTTP
 *
 * @param method         GET, PUT, POST, DELETE, etc
 * @param url            The remote connection string
 * @param headers        HTTP headers to be sent
 * @param params         Parameters for the get. Can be null.
 * @param inputStream    Source stream for retrieving request data
 * @param options        Any additional options for affecting request behaviour. Can NOT be null.
 * @param noChunkMaxSize The maximum size before chunking would need to be utilised. 0 disables check for chunking
 * @return ResponseWrapper
 * @throws Exception
 */
public static ResponseWrapper execRequest(String method, String url, Enumeration<Header> headers, NameValuePair[] params, InputStream inputStream, Map<String, String> options, long noChunkMaxSize) throws Exception {

    HttpClientBuilder httpBuilder = HttpClientBuilder.create();
    URL urlObj = new URL(url);
    /*
     * httpClient is used for this request only,
     * set a connection manager that manages just one connection.
     */
    if (urlObj.getProtocol().equalsIgnoreCase("https")) {
        /*
         * Note: registration of a custom SSLSocketFactory via httpBuilder.setSSLSocketFactory is ignored when a connection manager is set.
         * The custom SSLSocketFactory needs to be registered together with the connection manager.
         */
        SSLConnectionSocketFactory sslCsf = buildSslFactory(urlObj, options);
        httpBuilder.setConnectionManager(new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslCsf).build()));
    } else {
        httpBuilder.setConnectionManager(new BasicHttpClientConnectionManager());
    }

    RequestBuilder rb = getRequestBuilder(method, urlObj, params, headers);
    RequestConfig.Builder rcBuilder = buildRequestConfig(options);
    setProxyConfig(httpBuilder, rcBuilder, urlObj.getProtocol());
    rb.setConfig(rcBuilder.build());

    if (inputStream != null) {
        if (noChunkMaxSize > 0L) {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            long copied = IOUtils.copyLarge(inputStream, bout, 0L, noChunkMaxSize + 1, new byte[8192]);
            if (copied > noChunkMaxSize) {
                throw new IOException("Mime inputstream too big to put in memory (more than " + noChunkMaxSize + " bytes).");
            }
            ByteArrayEntity bae = new ByteArrayEntity(bout.toByteArray(), null);
            rb.setEntity(bae);
        } else {
            InputStreamEntity ise = new InputStreamEntity(inputStream);
            rb.setEntity(ise);
        }
    }
    final HttpUriRequest request = rb.build();

    String httpUser = options.get(HTTPUtil.PARAM_HTTP_USER);
    String httpPwd = options.get(HTTPUtil.PARAM_HTTP_PWD);
    if (httpUser != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(httpUser, httpPwd));
        httpBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }
    BasicHttpContext localcontext = new BasicHttpContext();
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);
    try (CloseableHttpClient httpClient = httpBuilder.build()) {
        ProfilerStub transferStub = Profiler.startProfile();
        try (CloseableHttpResponse response = httpClient.execute(request, localcontext)) {
            ResponseWrapper resp = new ResponseWrapper(response);
            Profiler.endProfile(transferStub);
            resp.setTransferTimeMs(transferStub.getMilliseconds());
            for (org.apache.http.Header header : response.getAllHeaders()) {
                resp.addHeaderLine(header.toString());
            }
            return resp;
        }
    }
}
 
Example 18
Source File: FileUploadDownloadClient.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
private static HttpUriRequest constructDeleteRequest(URI uri) {
  RequestBuilder requestBuilder = RequestBuilder.delete(uri).setVersion(HttpVersion.HTTP_1_1);
  setTimeout(requestBuilder, DELETE_REQUEST_SOCKET_TIMEOUT_MS);
  return requestBuilder.build();
}
 
Example 19
Source File: FileUploadDownloadClient.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
private static HttpUriRequest getSegmentCompletionProtocolRequest(URI uri, int socketTimeoutMs) {
  RequestBuilder requestBuilder = RequestBuilder.get(uri).setVersion(HttpVersion.HTTP_1_1);
  setTimeout(requestBuilder, socketTimeoutMs);
  return requestBuilder.build();
}
 
Example 20
Source File: RfRequestBuilder.java    From restfiddle with Apache License 2.0 4 votes vote down vote up
public HttpUriRequest build(RfRequestDTO requestDTO) {
String methodType = requestDTO.getMethodType();

RequestBuilder requestBuilder = RequestBuilder.create(methodType);

setUriWithParams(requestDTO, requestBuilder);

setHeaders(requestDTO, requestBuilder);

// Set Basic Authentication
basicAuthHandler.setBasicAuthWithBase64Encode(requestDTO, requestBuilder);

setRequestEntity(requestDTO, requestBuilder);

HttpUriRequest httpUriRequest = requestBuilder.build();
return httpUriRequest;
   }