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

The following examples show how to use org.apache.http.client.methods.RequestBuilder#setUri() . 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: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected RequestBuilder getRequestBuilder() throws HTTPException {
  if (this.methodurl == null)
    throw new HTTPException("Null url");
  RequestBuilder rb = null;
  switch (this.methodkind) {
    case Put:
      rb = RequestBuilder.put();
      break;
    case Post:
      rb = RequestBuilder.post();
      break;
    case Head:
      rb = RequestBuilder.head();
      break;
    case Options:
      rb = RequestBuilder.options();
      break;
    case Get:
    default:
      rb = RequestBuilder.get();
      break;
  }
  rb.setUri(this.methodurl);
  return rb;
}
 
Example 2
Source File: RawHttpComponentsClient.java    From rawhttp with Apache License 2.0 6 votes vote down vote up
public RawHttpResponse<CloseableHttpResponse> send(RawHttpRequest request) throws IOException {
    RequestBuilder builder = RequestBuilder.create(request.getMethod());
    builder.setUri(request.getUri());
    builder.setVersion(toProtocolVersion(request.getStartLine().getHttpVersion()));
    request.getHeaders().getHeaderNames().forEach((name) ->
            request.getHeaders().get(name).forEach(value ->
                    builder.addHeader(new BasicHeader(name, value))));

    request.getBody().ifPresent(b -> builder.setEntity(new InputStreamEntity(b.asRawStream())));

    CloseableHttpResponse response = httpClient.execute(builder.build());

    RawHttpHeaders headers = readHeaders(response);
    StatusLine statusLine = adaptStatus(response.getStatusLine());

    @Nullable LazyBodyReader body;
    if (response.getEntity() != null) {
        FramedBody framedBody = http.getFramedBody(statusLine, headers);
        body = new LazyBodyReader(framedBody, response.getEntity().getContent());
    } else {
        body = null;
    }

    return new RawHttpResponse<>(response, request, statusLine, headers, body);
}
 
Example 3
Source File: ApacheHttpRequestBuilderTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Build a {@link HttpUriRequest} from a {@link GenericRecord}
 */
public void testBuildWriteRequest()
    throws IOException {
  String urlTemplate = "http://www.test.com/a/part1:${part1}/a/part2:${part2}";
  String verb = "post";
  ApacheHttpRequestBuilder builder = spy(new ApacheHttpRequestBuilder(urlTemplate, verb, "application/json"));
  ArgumentCaptor<RequestBuilder> requestBuilderArgument = ArgumentCaptor.forClass(RequestBuilder.class);

  Queue<BufferedRecord<GenericRecord>> queue = HttpTestUtils.createQueue(1, false);
  AsyncRequest<GenericRecord, HttpUriRequest> request = builder.buildRequest(queue);
  verify(builder).build(requestBuilderArgument.capture());

  RequestBuilder expected = RequestBuilder.post();
  expected.setUri("http://www.test.com/a/part1:01/a/part2:02?param1=01");
  String payloadStr = "{\"id\":\"id0\"}";
  expected.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType())
      .setEntity(new StringEntity(payloadStr, ContentType.APPLICATION_JSON));

  // Compare HttpUriRequest
  HttpTestUtils.assertEqual(requestBuilderArgument.getValue(), expected);
  Assert.assertEquals(request.getRecordCount(), 1);
  Assert.assertEquals(queue.size(), 0);
}
 
Example 4
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 5
Source File: HTTPUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static RequestBuilder getRequestBuilder(String method, URL urlObj, NameValuePair[] params, Enumeration<Header> headers) throws URISyntaxException {

        RequestBuilder req = null;
        if (method == null || method.equalsIgnoreCase(Method.GET)) {
            //default get
            req = RequestBuilder.get();
        } else if (method.equalsIgnoreCase(Method.POST)) {
            req = RequestBuilder.post();
        } else if (method.equalsIgnoreCase(Method.HEAD)) {
            req = RequestBuilder.head();
        } else if (method.equalsIgnoreCase(Method.PUT)) {
            req = RequestBuilder.put();
        } else if (method.equalsIgnoreCase(Method.DELETE)) {
            req = RequestBuilder.delete();
        } else if (method.equalsIgnoreCase(Method.TRACE)) {
            req = RequestBuilder.trace();
        } else {
            throw new IllegalArgumentException("Illegal HTTP Method: " + method);
        }
        req.setUri(urlObj.toURI());
        if (params != null && params.length > 0) {
            req.addParameters(params);
        }
        if (headers != null) {
            boolean removeHeaderFolding = "true".equals(Properties.getProperty(HTTP_PROP_REMOVE_HEADER_FOLDING, "true"));
            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                String headerValue = header.getValue();
                if (removeHeaderFolding) {
                    headerValue = headerValue.replaceAll("\r\n[ \t]*", " ");
                }
                req.setHeader(header.getName(), headerValue);
            }
        }
        return req;
    }
 
Example 6
Source File: ApacheHttpRequestBuilder.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Build a write request from a single record
 */
private ApacheHttpRequest<GenericRecord> buildWriteRequest(BufferedRecord<GenericRecord> record) {
  if (record == null) {
    return null;
  }

  ApacheHttpRequest<GenericRecord> request = new ApacheHttpRequest<>();
  HttpOperation httpOperation = HttpUtils.toHttpOperation(record.getRecord());

  // Set uri
  URI uri = HttpUtils.buildURI(urlTemplate, httpOperation.getKeys(), httpOperation.getQueryParams());
  if (uri == null) {
    return null;
  }

  RequestBuilder builder = RequestBuilder.create(verb.toUpperCase());
  builder.setUri(uri);

  // Set headers
  Map<String, String> headers = httpOperation.getHeaders();
  if (headers != null && headers.size() != 0) {
    for (Map.Entry<String, String> header : headers.entrySet()) {
      builder.setHeader(header.getKey(), header.getValue());
    }
  }

  // Add payload
  int bytesWritten = addPayload(builder, httpOperation.getBody());
  if (bytesWritten == -1) {
    throw new RuntimeException("Fail to write payload into request");
  }

  request.setRawRequest(build(builder));
  request.markRecord(record, bytesWritten);
  return request;
}
 
Example 7
Source File: SalesforceRestWriter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * For single request, creates HttpUriRequest and decides post/patch operation based on input parameter.
 *
 * For batch request, add the record into JsonArray as a subrequest and only creates HttpUriRequest with POST method if it filled the batch size.
 * {@inheritDoc}
 * @see org.apache.gobblin.writer.http.RestJsonWriter#onNewRecord(org.apache.gobblin.converter.rest.RestEntry)
 */
@Override
public Optional<HttpUriRequest> onNewRecord(RestEntry<JsonObject> record) {
  Preconditions.checkArgument(!StringUtils.isEmpty(accessToken), "Access token has not been acquired.");
  Preconditions.checkNotNull(record, "Record should not be null");

  RequestBuilder builder = null;
  JsonObject payload = null;

  if (batchSize > 1) {
    if (!batchRecords.isPresent()) {
      batchRecords = Optional.of(new JsonArray());
    }
    batchRecords.get().add(newSubrequest(record));

    if (batchRecords.get().size() < batchSize) { //No need to send. Return absent.
      return Optional.absent();
    }

    payload = newPayloadForBatch();
    builder = RequestBuilder.post().setUri(combineUrl(getCurServerHost(), batchResourcePath));
  } else {
    switch (operation) {
      case INSERT_ONLY_NOT_EXIST:
        builder = RequestBuilder.post();
        break;
      case UPSERT:
        builder = RequestBuilder.patch();
        break;
      default:
        throw new IllegalArgumentException(operation + " is not supported.");
    }
    builder.setUri(combineUrl(getCurServerHost(), record.getResourcePath()));
    payload = record.getRestEntryVal();
  }
  return Optional.of(newRequest(builder, payload));
}
 
Example 8
Source File: RfRequestBuilder.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
private void setUriWithParams(RfRequestDTO requestDTO, RequestBuilder requestBuilder) {
String apiUrl = requestDTO.getEvaluatedApiUrl();
if(apiUrl == null || apiUrl.equals("")){
    apiUrl = requestDTO.getApiUrl();
}
List<UrlParamDTO> urlParams = requestDTO.getUrlParams();
if (urlParams != null && !urlParams.isEmpty()) {
    apiUrl = buildUrlWithParams(apiUrl, urlParams);
}
requestBuilder.setUri(apiUrl);
// TODO : Shall we set this API URL in UI Layer itself?
//requestDTO.setApiUrl(apiUrl);
   }
 
Example 9
Source File: HttpClaimInformationPointProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private InputStream executeRequest(HttpFacade httpFacade) {
    String method = config.get("method").toString();

    if (method == null) {
        method = "GET";
    }

    RequestBuilder builder = null;

    if ("GET".equalsIgnoreCase(method)) {
        builder = RequestBuilder.get();
    } else {
        builder = RequestBuilder.post();
    }

    builder.setUri(config.get("url").toString());

    byte[] bytes = new byte[0];

    try {
        setParameters(builder, httpFacade);

        if (config.containsKey("headers")) {
            setHeaders(builder, httpFacade);
        }

        HttpResponse response = httpClient.execute(builder.build());
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            bytes = EntityUtils.toByteArray(entity);
        }

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode < 200 || statusCode >= 300) {
            throw new HttpResponseException("Unexpected response from server: " + statusCode + " / " + statusLine.getReasonPhrase(), statusCode, statusLine.getReasonPhrase(), bytes);
        }

        return new ByteArrayInputStream(bytes);
    } catch (Exception cause) {
        try {
            throw new RuntimeException("Error executing http method [" + builder + "]. Response : " + StreamUtil.readString(new ByteArrayInputStream(bytes), Charset.forName("UTF-8")), cause);
        } catch (Exception e) {
            throw new RuntimeException("Error executing http method [" + builder + "]", cause);
        }
    }
}