下面列出了org.apache.http.client.methods.HttpRequestBase#setHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void setHandshakeProperties(final HttpRequestBase httpRequest) {
if (compress) {
httpRequest.setHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION, "true");
}
if (requestExpirationMillis > 0) {
httpRequest.setHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION, String.valueOf(requestExpirationMillis));
}
if (batchCount > 0) {
httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_COUNT, String.valueOf(batchCount));
}
if (batchSize > 0) {
httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_SIZE, String.valueOf(batchSize));
}
if (batchDurationMillis > 0) {
httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_DURATION, String.valueOf(batchDurationMillis));
}
}
private HttpResponse makeHTTPConnection() throws IOException, NullPointerException {
if (fileURI == null) throw new NullPointerException("No file URI specified");
HttpClient client = HttpClientBuilder.create().build();
HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
requestMethod.setURI(fileURI);
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, getWebDriverCookies(driver.manage().getCookies()));
requestMethod.setHeader("User-Agent", getWebDriverUserAgent());
if (null != urlParameters && (
httpRequestMethod.equals(RequestType.PATCH) ||
httpRequestMethod.equals(RequestType.POST) ||
httpRequestMethod.equals(RequestType.PUT))
) {
((HttpEntityEnclosingRequestBase) requestMethod).setEntity(new UrlEncodedFormEntity(urlParameters));
}
return client.execute(requestMethod, localContext);
}
public void sign(HttpRequestBase req) throws IOException {
String payload = null;
Charset charset = Charset.defaultCharset();
if (HttpEntityEnclosingRequestBase.class.isAssignableFrom(req.getClass())) {
HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) req;
HttpEntity entity = requestBase.getEntity();
if (entity.getContentLength() > 0) {
if (!entity.isRepeatable()) {
throw new IOException(
"The signer needs to read the request payload but the input stream of this request cannot be read multiple times. Please provide the payload using a separate argument or ensure that the entity is repeatable.");
}
ContentType contentType = ContentType.get(entity);
charset = contentType.getCharset();
payload = EntityUtils.toString(entity, contentType.getCharset());
}
}
String authHeader = OAuth.getAuthorizationHeader(req.getURI(), req.getMethod(), payload, charset, consumerKey, signingKey);
req.setHeader(OAuth.AUTHORIZATION_HEADER_NAME, authHeader);
}
/**
* 设置header
*
* @param method method
* @param headers headers
*/
private static void setHeader(HttpRequestBase method, Map<String, String> headers) {
if (null != headers) {
Iterator<String> keys = headers.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = headers.get(key);
method.setHeader(key, value);
}
}
}
private void addCommonHeaders(HttpRequestBase httpMtd, Map<String, String> metadata) {
httpMtd.setHeader(CLIENT_IP_HEADER_NAME, clientIp);
String app = getMetricConfig().getString(LookoutConfig.APP_NAME);
if (StringUtils.isNotEmpty(app)) {
httpMtd.setHeader(APP_HEADER_NAME, app);
}
if (metadata == null) {
return;
}
for (Map.Entry<String, String> entry : metadata.entrySet()) {
httpMtd.setHeader(entry.getKey(), entry.getValue());
}
}
/**
* Execute http client request.
*/
protected HttpResponse execute(final Context context, final HttpClient client, final HttpRequestBase request)
throws IOException
{
String bearerToken = getRepository().facet(HttpClientFacet.class).getBearerToken();
if (StringUtils.isNotBlank(bearerToken)) {
request.setHeader("Authorization", "Bearer " + bearerToken);
}
return super.execute(context, client, request);
}
public CloseableHttpResponse execute(HttpRequestBase httpMethod) throws IOException {
GoAgentServerHttpClient client = httpClientFactory.httpClient();
httpMethod.setHeader("X-Agent-GUID", agentRegistry.uuid());
httpMethod.setHeader("Authorization", agentRegistry.token());
CloseableHttpResponse response = client.execute(httpMethod);
LOGGER.info("Got back {} from server", response.getStatusLine().getStatusCode());
return response;
}
private CloseableHttpResponse doRequest(final HttpRequestBase request) throws IOException {
if (log.isDebugEnabled()) {
log.debug(request.getMethod() + " " + request.getURI());
}
Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(check.getSocketTimeout()).setConnectTimeout(check.getConnectionTimeout());
if (check.getHttpProxyServer() != null && !check.getHttpProxyServer().isEmpty()) {
HttpHost httpProxy = new HttpHost(check.getHttpProxyServer(), check.getHttpProxyPort());
requestConfigBuilder.setProxy(httpProxy);
}
RequestConfig requestConfig = requestConfigBuilder.build();
request.setConfig(requestConfig);
String header = check.getHeader();
if(null!=header && header.length()>0 && header.contains(":"))
{
log.info("header:" + header);
String[] headerKV = header.split(":");
request.setHeader(headerKV[0],headerKV[1]);
}
CloseableHttpResponse response = null;
try {
request.setHeader("User-Agent", check.getUserAgent());
response = httpClient.execute(request);
} catch (SSLHandshakeException ex) {
// ignore ValidatorException -> thrown when Java cannot validate
// certificate
log.error("java could not validate certificate for URL: " + request.getURI(), ex);
return null;
}
if (log.isDebugEnabled()) {
log.debug("status: " + response.getStatusLine());
}
return response;
}
/**
* 设置头信息
*
* @param headers
* @param httpPost
*/
private static void setHeaders(Map<String, String> headers, HttpRequestBase httpPost) {
if (headers != null) {
Iterator<Entry<String, String>> it = headers.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
}
protected static void setHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
httpRequest.setHeader("User-Agent", "GH::watch");
if (headers != null) {
for (Entry<String, String> he : headers.entrySet()) {
Log.d(TAG, "Set request header " + he.getKey() + ":" + he.getValue());
httpRequest.setHeader(he.getKey(), he.getValue());
}
}
}
protected HttpResponse callUri(
final ODataHttpMethod httpMethod, final String uri,
final String additionalHeader, final String additionalHeaderValue,
final String requestBody, final String requestContentType,
final HttpStatusCodes expectedStatusCode) throws Exception {
HttpRequestBase request =
httpMethod == ODataHttpMethod.GET ? new HttpGet() :
httpMethod == ODataHttpMethod.DELETE ? new HttpDelete() :
httpMethod == ODataHttpMethod.POST ? new HttpPost() :
httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch();
request.setURI(URI.create(getEndpoint() + uri));
if (additionalHeader != null) {
request.addHeader(additionalHeader, additionalHeaderValue);
}
if (requestBody != null) {
((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody));
request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType);
}
final HttpResponse response = getHttpClient().execute(request);
assertNotNull(response);
assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode());
if (expectedStatusCode == HttpStatusCodes.OK) {
assertNotNull(response.getEntity());
assertNotNull(response.getEntity().getContent());
} else if (expectedStatusCode == HttpStatusCodes.CREATED) {
assertNotNull(response.getEntity());
assertNotNull(response.getEntity().getContent());
assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION));
} else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) {
assertTrue(response.getEntity() == null || response.getEntity().getContent() == null);
}
return response;
}
protected static void addAuthHeader(HttpRequestBase method, Context parent) {
String loginPref = Preferences.getPreference(parent,
Preferences.MY_CHANNEL_JID);
String passPref = Preferences.getPreference(parent,
Preferences.PASSWORD);
String auth = loginPref + ":" + passPref;
String authToken = Base64.encodeToString(auth.getBytes(),
Base64.NO_WRAP);
method.setHeader("Authorization", "Basic " + authToken);
}
private void setBasicAuthHeader(@SuppressWarnings({"rawtypes"})SolrRequest request, HttpRequestBase method) throws UnsupportedEncodingException {
if (request.getBasicAuthUser() != null && request.getBasicAuthPassword() != null) {
String userPass = request.getBasicAuthUser() + ":" + request.getBasicAuthPassword();
String encoded = Base64.byteArrayToBase64(userPass.getBytes(FALLBACK_CHARSET));
method.setHeader(new BasicHeader("Authorization", "Basic " + encoded));
}
}
private void setContentTypeToApplicationJson(HttpRequestBase request) {
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
}
protected static void addAcceptJSONHeader(HttpRequestBase method) {
method.setHeader("Accept", "application/json");
}
protected static void setJsonContentTypeHeader(HttpRequestBase request) {
request.setHeader("Content-Type", "application/json; charset=utf-8");
}
protected CloseableHttpResponse runRequest(HttpRequestBase request) throws IOException {
request.setHeader("Authorization", "Bearer " + token);
return client.execute(request);
}
@Override
protected void addCustomHTTPHeaders(HttpRequestBase request) {
request.setHeader(HTTP_HEADER_API_SIGNATURE, getRequestSignature());
request.setHeader(HTTP_HEADER_API_TIMESTAMP, mTimestamp);
}
private static void addDefineHeaders(HttpRequestBase req,String sessionId){
req.setHeader("X-SessionId",sessionId);
req.addHeader("Cache-Control","no-cache no-store");
req.addHeader("Pragma","no-cache");
}
/**
* Set basic auth header to http request
*
* @param httpRequestBase http request
* @param username username
* @param password password
*/
public static void setAuthHeader(HttpRequestBase httpRequestBase, String username, String password) {
String basicAuthHeader = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
httpRequestBase.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), AUTH_TYPE_BASIC + basicAuthHeader);
}