org.apache.http.client.methods.RequestBuilder#setHeader()源码实例Demo

下面列出了org.apache.http.client.methods.RequestBuilder#setHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: zerocode   文件: BasicHttpClient.java
/**
 * 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;
}
 
源代码2 项目: fc-java-sdk   文件: AsyncInternalClient.java
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());
    }
}
 
源代码3 项目: rdf4j   文件: RDF4JProtocolSession.java
@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();
}
 
源代码4 项目: OpenAs2App   文件: HTTPUtil.java
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;
    }
 
/**
 * 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;
}
 
/**
 * 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();
}
 
源代码7 项目: incubator-pinot   文件: GitHubAPICaller.java
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();
}
 
@Override
public void executeStep(PluginStepContext pluginStepContext, Map<String, Object> options) throws StepException {
    String authHeader = null;

    // Parse out the options
    String remoteUrl = options.containsKey("remoteUrl") ? options.get("remoteUrl").toString() : null;
    String method = options.containsKey("method") ? options.get("method").toString() : null;
    String authentication = options.containsKey("authentication") ? options.get("authentication").toString() : AUTH_NONE;
    Integer timeout = options.containsKey("timeout") ? Integer.parseInt(options.get("timeout").toString()) : DEFAULT_TIMEOUT;

    if(remoteUrl == null || method == null) {
        throw new StepException("Remote URL and Method are required.", StepFailureReason.ConfigurationFailure);
    }

    if(authentication.equals(AUTH_BASIC)) {
        // Setup the authentication header for BASIC
        String username = options.containsKey("username") ? options.get("username").toString() : null;
        String password = options.containsKey("password") ? options.get("password").toString() : null;
        if(username == null || password == null) {
            throw new StepException("Username and password not provided for BASIC Authentication",
                    StepFailureReason.ConfigurationFailure);
        }

        authHeader = username + ":" + password;
        
        //As per RFC2617 the Basic Authentication standard has to send the credentials Base64 encoded. 
        authHeader = "Basic " + com.dtolabs.rundeck.core.utils.Base64.encode(authHeader);
    } else if (authentication.equals(AUTH_OAUTH2)) {
        // Get an OAuth token and setup the auth header for OAuth
        String tokenEndpoint = options.containsKey("oauthTokenEndpoint") ? options.get("oauthTokenEndpoint").toString() : null;
        String validateEndpoint = options.containsKey("oauthValidateEndpoint") ? options.get("oauthValidateEndpoint").toString() : null;
        String clientId = options.containsKey("username") ? options.get("username").toString() : null;
        String clientSecret = options.containsKey("password") ? options.get("password").toString() : null;

        if(tokenEndpoint == null) {
            throw new StepException("Token endpoint not provided for OAuth 2.0 Authentication.",
                    StepFailureReason.ConfigurationFailure);
        }

        String clientKey = clientId + "@" + tokenEndpoint;
        String accessToken;

        // Another thread may be trying to do the same thing.
        synchronized(HttpWorkflowStepPlugin.oauthClients) {
            OAuthClient client;

            if(HttpWorkflowStepPlugin.oauthClients.containsKey(clientKey)) {
                // Update the existing client with our options if it exists.
                // We do this so that changes to configuration will always
                // update clients on next run.
                log.trace("Found existing OAuth client with key " + clientKey);
                client = HttpWorkflowStepPlugin.oauthClients.get(clientKey);
                client.setCredentials(clientId, clientSecret);
                client.setValidateEndpoint(validateEndpoint);
            } else {
                // Create a brand new client
                log.trace("Creating new OAuth client with key " + clientKey);
                client = new OAuthClient(OAuthClient.GrantType.CLIENT_CREDENTIALS);
                client.setCredentials(clientId, clientSecret);
                client.setTokenEndpoint(tokenEndpoint);
                client.setValidateEndpoint(validateEndpoint);
            }

            // Grab the access token
            try {
                log.trace("Attempting to fetch access token...");
                accessToken = client.getAccessToken();
            } catch(Exception ex) {
                StepException se = new StepException("Error obtaining OAuth Access Token: " + ex.getMessage(),
                        Reason.OAuthFailure);
                se.initCause(ex);
                throw se;
            }

            HttpWorkflowStepPlugin.oauthClients.put(clientKey, client);
        }

        authHeader = "Bearer " + accessToken;
    }

    // Setup the request and process it.
    RequestBuilder request = RequestBuilder.create(method)
            .setUri(remoteUrl)
            .setConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .setSocketTimeout(timeout)
                    .build());

    log.debug("Creating HTTP " + request.getMethod() + " request to " + request.getUri());

    if(authHeader != null) {
        log.trace("Authentication header set to " + authHeader);
        request.setHeader("Authorization", authHeader);
    }

    this.doRequest(options, request.build(), 1);
}