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

The following examples show how to use org.apache.http.client.methods.RequestBuilder#post() . 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: JSON.java    From validatar with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a HttpUriRequest based on the metadata configuration.
 * @param metadata The metadata configuration.
 * @return A configured request object.
 */
private HttpUriRequest createRequest(Map<String, String> metadata) {
    String verb = metadata.getOrDefault(VERB_KEY, DEFAULT_VERB);
    String url = metadata.get(URL_KEY);
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("The " + URL_KEY + " must be provided and contain a valid url.");
    }
    RequestBuilder builder;
    if (GET.equals(verb)) {
        builder = RequestBuilder.get(url);
    } else if (POST.equals(verb)) {
        builder = RequestBuilder.post(url);
        String body = metadata.getOrDefault(BODY_KEY, EMPTY_BODY);
        builder.setEntity(new StringEntity(body, Charset.defaultCharset()));
    } else {
        throw new UnsupportedOperationException("This HTTP method is not currently supported: " + verb);
    }
    // Everything else is assumed to be a header
    metadata.entrySet().stream().filter(entry -> !KNOWN_KEYS.contains(entry.getKey()))
                                .forEach(entry -> builder.addHeader(entry.getKey(), entry.getValue()));
    return builder.build();
}
 
Example 3
Source File: HttpClientDownloader.java    From zongtui-webcrawler with GNU General Public License v2.0 6 votes vote down vote up
protected RequestBuilder selectRequestMethod(Request request) {
    String method = request.getMethod();
    if (method == null || method.equalsIgnoreCase(HttpConstant.Method.GET)) {
        //default get
        return RequestBuilder.get();
    } else if (method.equalsIgnoreCase(HttpConstant.Method.POST)) {
        RequestBuilder requestBuilder = RequestBuilder.post();
        NameValuePair[] nameValuePair = (NameValuePair[]) request.getExtra("nameValuePair");
        if (nameValuePair != null && nameValuePair.length > 0) {
            requestBuilder.addParameters(nameValuePair);
        }
        return requestBuilder;
    } else if (method.equalsIgnoreCase(HttpConstant.Method.HEAD)) {
        return RequestBuilder.head();
    } else if (method.equalsIgnoreCase(HttpConstant.Method.PUT)) {
        return RequestBuilder.put();
    } else if (method.equalsIgnoreCase(HttpConstant.Method.DELETE)) {
        return RequestBuilder.delete();
    } else if (method.equalsIgnoreCase(HttpConstant.Method.TRACE)) {
        return RequestBuilder.trace();
    }
    throw new IllegalArgumentException("Illegal HTTP Method " + method);
}
 
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
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);
        }
    }
}