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

The following examples show how to use org.apache.http.client.methods.RequestBuilder#setEntity() . 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 void setcontent(RequestBuilder rb) {
  switch (this.methodkind) {
    case Put:
      if (this.content != null)
        rb.setEntity(this.content);
      break;
    case Post:
      if (this.content != null)
        rb.setEntity(this.content);
      break;
    case Head:
    case Get:
    case Options:
    default:
      break;
  }
  this.content = null; // do not reuse
}
 
Example 2
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 3
Source File: BasicHttpClient.java    From zerocode with Apache License 2.0 6 votes vote down vote up
/**
 * This is how framework makes the KeyValue pair when "application/x-www-form-urlencoded" headers
 * is passed in the request.  In case you want to build or prepare the requests differently,
 * you can override this method via @UseHttpClient(YourCustomHttpClient.class).
 *
 * @param httpUrl
 * @param methodName
 * @param reqBodyAsString
 * @return
 * @throws IOException
 */
public RequestBuilder createFormUrlEncodedRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) throws IOException {
    RequestBuilder requestBuilder = RequestBuilder
            .create(methodName)
            .setUri(httpUrl);
    if (reqBodyAsString != null) {
        Map<String, Object> reqBodyMap = HelperJsonUtils.readObjectAsMap(reqBodyAsString);
        List<NameValuePair> reqBody = new ArrayList<>();
         for(String key : reqBodyMap.keySet()) {
             reqBody.add(new BasicNameValuePair(key, reqBodyMap.get(key).toString()));
         }
         HttpEntity httpEntity = new UrlEncodedFormEntity(reqBody);
         requestBuilder.setEntity(httpEntity);
        requestBuilder.setHeader(CONTENT_TYPE, APPLICATION_FORM_URL_ENCODED);
    }
    return requestBuilder;
}
 
Example 4
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 5
Source File: HttpDownloadHandler.java    From cetty with Apache License 2.0 5 votes vote down vote up
private RequestBuilder addFormParams(RequestBuilder requestBuilder, Seed seed) {
    if (seed.getRequestBody() != null) {
        ByteArrayEntity entity = new ByteArrayEntity(seed.getRequestBody().getBody());
        entity.setContentType(seed.getRequestBody().getContentType());
        requestBuilder.setEntity(entity);
    }
    return requestBuilder;
}
 
Example 6
Source File: AsyncInternalClient.java    From fc-java-sdk with MIT License 5 votes vote down vote up
private void copyToRequest(HttpRequest request, RequestBuilder requestBuilder){
    if (request.getPayload() != null) {
        requestBuilder.setEntity(new ByteArrayEntity(request.getPayload()));
    }

    Map<String, String> headers = request.getHeaders();
    for(Map.Entry<String, String> item : headers.entrySet()) {
        requestBuilder.setHeader(item.getKey(), item.getValue());
    }
}
 
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: BasicHttpClient.java    From zerocode with Apache License 2.0 5 votes vote down vote up
/**
 * This is the usual http request builder most widely used using Apache Http Client. In case you want to build
 * or prepare the requests differently, you can override this method.
 *
 * Please see the following request builder to handle file uploads.
 *     - BasicHttpClient#createFileUploadRequestBuilder(java.lang.String, java.lang.String, java.lang.String)
 *
 * You can override this method via @UseHttpClient(YourCustomHttpClient.class)
 *
 * @param httpUrl
 * @param methodName
 * @param reqBodyAsString
 * @return
 */
public RequestBuilder createDefaultRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) {
    RequestBuilder requestBuilder = RequestBuilder
            .create(methodName)
            .setUri(httpUrl);

    if (reqBodyAsString != null) {
        HttpEntity httpEntity = EntityBuilder.create()
                .setContentType(APPLICATION_JSON)
                .setText(reqBodyAsString)
                .build();
        requestBuilder.setEntity(httpEntity);
    }
    return requestBuilder;
}
 
Example 10
Source File: ApacheHttpRequestBuilder.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Add payload to request. By default, payload is sent as application/json
 */
protected int addPayload(RequestBuilder builder, String payload) {
  if (payload == null || payload.length() == 0) {
    return 0;
  }


  builder.setHeader(HttpHeaders.CONTENT_TYPE, contentType.getMimeType());
  builder.setEntity(new StringEntity(payload, contentType));
  return payload.length();
}
 
Example 11
Source File: HttpUriRequestConverter.java    From webmagic with Apache License 2.0 5 votes vote down vote up
private RequestBuilder addFormParams(RequestBuilder requestBuilder, Request request) {
    if (request.getRequestBody() != null) {
        ByteArrayEntity entity = new ByteArrayEntity(request.getRequestBody().getBody());
        entity.setContentType(request.getRequestBody().getContentType());
        requestBuilder.setEntity(entity);
    }
    return requestBuilder;
}
 
Example 12
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 13
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 14
Source File: FileUploadUtils.java    From zerocode with Apache License 2.0 3 votes vote down vote up
public static RequestBuilder createUploadRequestBuilder(String httpUrl, String methodName, MultipartEntityBuilder multipartEntityBuilder) {

        RequestBuilder uploadRequestBuilder = RequestBuilder
                .create(methodName)
                .setUri(httpUrl);

        HttpEntity reqEntity = multipartEntityBuilder.build();

        uploadRequestBuilder.setEntity(reqEntity);

        return uploadRequestBuilder;
    }