List of usage examples for com.google.common.net HttpHeaders USER_AGENT
String USER_AGENT
To view the source code for com.google.common.net HttpHeaders USER_AGENT.
Click Source Link
From source file:org.hashes.CollisionInjector.java
protected void addRequestHeaders(final int contentLength, final StringBuilder payloadBuilder) { // http://www.ietf.org/rfc/rfc2616.txt // Each header field consists of a name followed by a colon (":") and the field value. Field names are // case-insensitive. final Locale locale = Locale.ENGLISH; final Map<String, String> defaultHeaders = new LinkedHashMap<String, String>(); defaultHeaders.put(HttpHeaders.HOST.toLowerCase(locale), this.configuration.getTarget().getHost()); defaultHeaders.put(HttpHeaders.CONTENT_TYPE.toLowerCase(locale), "application/x-www-form-urlencoded"); defaultHeaders.put(HttpHeaders.ACCEPT_CHARSET.toLowerCase(locale), this.configuration.getCharset().name()); defaultHeaders.put(HttpHeaders.CONTENT_LENGTH.toLowerCase(locale), String.valueOf(contentLength)); defaultHeaders.put(HttpHeaders.USER_AGENT.toLowerCase(locale), "hashes"); defaultHeaders.put(HttpHeaders.ACCEPT.toLowerCase(locale), "*/*"); for (final Entry<String, String> externalHeaders : this.configuration.getHeaders().entrySet()) { defaultHeaders.put(externalHeaders.getKey().toLowerCase(locale), externalHeaders.getValue()); }/*ww w . j ava2 s . c om*/ for (final Entry<String, String> header : defaultHeaders.entrySet()) { payloadBuilder.append(header.getKey()); payloadBuilder.append(": "); payloadBuilder.append(header.getValue()); payloadBuilder.append("\r\n"); } payloadBuilder.append("\r\n"); }
From source file:org.sonatype.nexus.httpclient.config.ConfigurationCustomizer.java
/** * Apply connection configuration to plan. *///ww w . ja va 2s .com private void apply(final ConnectionConfiguration connection, final HttpClientPlan plan) { if (connection.getTimeout() != null) { int timeout = connection.getTimeout().toMillisI(); plan.getSocket().setSoTimeout(timeout); plan.getRequest().setConnectTimeout(timeout); plan.getRequest().setSocketTimeout(timeout); } if (connection.getMaximumRetries() != null) { plan.getClient() .setRetryHandler(new StandardHttpRequestRetryHandler(connection.getMaximumRetries(), false)); } if (connection.getUserAgentSuffix() != null) { checkState(plan.getUserAgent() != null, "Default User-Agent not set"); plan.getHeaders().put(HttpHeaders.USER_AGENT, plan.getUserAgent() + " " + connection.getUserAgentSuffix()); } if (Boolean.TRUE.equals(connection.getUseTrustStore())) { plan.getAttributes().put(SSLContextSelector.USE_TRUST_STORE, Boolean.TRUE); } }
From source file:org.jclouds.s3.filters.Aws4SignerForAuthorizationHeader.java
protected HttpRequest sign(HttpRequest request) throws HttpException { checkNotNull(request, "request is not ready to sign"); checkNotNull(request.getEndpoint(), "request is not ready to sign, request.endpoint not present."); Payload payload = request.getPayload(); // get host from request endpoint. String host = request.getEndpoint().getHost(); Date date = timestampProvider.get(); String timestamp = timestampFormat.format(date); String datestamp = dateFormat.format(date); String service = serviceAndRegion.service(); String region = serviceAndRegion.region(host); String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request"); HttpRequest.Builder<?> requestBuilder = request.toBuilder() // .removeHeader(AUTHORIZATION) // remove Authorization .removeHeader(DATE); // remove date ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap .<String, String>naturalOrder(); // Content Type // content-type is not a required signing param. However, examples use this, so we include it to ease testing. String contentType = getContentType(request); if (!Strings.isNullOrEmpty(contentType)) { requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType); signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType); }/* www . ja v a2 s. c om*/ // Content-Length for PUT or POST request http method String contentLength = getContentLength(request); if (!Strings.isNullOrEmpty(contentLength)) { requestBuilder.replaceHeader(HttpHeaders.CONTENT_LENGTH, contentLength); signedHeadersBuilder.put(HttpHeaders.CONTENT_LENGTH.toLowerCase(), contentLength); } // Content MD5 String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5); if (payload != null) { HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode(); if (md5 != null) { contentMD5 = BaseEncoding.base64().encode(md5.asBytes()); } } if (contentMD5 != null) { requestBuilder.replaceHeader(CONTENT_MD5, contentMD5); signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5); } // host requestBuilder.replaceHeader(HttpHeaders.HOST, host); signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host); // user-agent if (request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) { signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(), request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT)); } // all x-amz-* headers appendAmzHeaders(request, signedHeadersBuilder); // x-amz-security-token Credentials credentials = creds.get(); if (credentials instanceof SessionCredentials) { String token = SessionCredentials.class.cast(credentials).getSessionToken(); requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token); signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token); } // x-amz-content-sha256 String contentSha256 = getPayloadHash(request); requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256); signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256); // put x-amz-date requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp); signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp); ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build(); String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders, timestamp, credentialScope, contentSha256); signatureWire.getWireLog().debug("<< " + stringToSign); byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service); String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey)); StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(" "); authorization.append("Credential=").append(Joiner.on("/").join(credentials.identity, credentialScope)) .append(", "); authorization.append("SignedHeaders=").append(Joiner.on(";").join(signedHeaders.keySet())).append(", "); authorization.append("Signature=").append(signature); return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString()).build(); }
From source file:com.google.zxing.web.DecodeServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageURIString = request.getParameter("u"); if (imageURIString == null || imageURIString.isEmpty()) { log.info("URI was empty"); errorResponse(request, response, "badurl"); return;/* w ww . j av a2 s. co m*/ } imageURIString = imageURIString.trim(); for (CharSequence substring : blockedURLSubstrings) { if (imageURIString.contains(substring)) { log.info("Disallowed URI " + imageURIString); errorResponse(request, response, "badurl"); return; } } URI imageURI; try { imageURI = new URI(imageURIString); // Assume http: if not specified if (imageURI.getScheme() == null) { imageURI = new URI("http://" + imageURIString); } } catch (URISyntaxException urise) { log.info("URI " + imageURIString + " was not valid: " + urise); errorResponse(request, response, "badurl"); return; } // Shortcut for data URI if ("data".equals(imageURI.getScheme())) { try { BufferedImage image = ImageReader.readDataURIImage(imageURI); processImage(image, request, response); } catch (IOException ioe) { log.info(ioe.toString()); errorResponse(request, response, "badurl"); } return; } URL imageURL; try { imageURL = imageURI.toURL(); } catch (MalformedURLException ignored) { log.info("URI was not valid: " + imageURIString); errorResponse(request, response, "badurl"); return; } String protocol = imageURL.getProtocol(); if (!"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) { log.info("URI was not valid: " + imageURIString); errorResponse(request, response, "badurl"); return; } HttpURLConnection connection; try { connection = (HttpURLConnection) imageURL.openConnection(); } catch (IllegalArgumentException ignored) { log.info("URI could not be opened: " + imageURL); errorResponse(request, response, "badurl"); return; } connection.setAllowUserInteraction(false); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestProperty(HttpHeaders.USER_AGENT, "zxing.org"); connection.setRequestProperty(HttpHeaders.CONNECTION, "close"); try { connection.connect(); } catch (IOException | IllegalArgumentException e) { // Encompasses lots of stuff, including // java.net.SocketException, java.net.UnknownHostException, // javax.net.ssl.SSLPeerUnverifiedException, // org.apache.http.NoHttpResponseException, // org.apache.http.client.ClientProtocolException, log.info(e.toString()); errorResponse(request, response, "badurl"); return; } try (InputStream is = connection.getInputStream()) { try { if (connection.getResponseCode() != HttpServletResponse.SC_OK) { log.info("Unsuccessful return code: " + connection.getResponseCode()); errorResponse(request, response, "badurl"); return; } if (connection.getHeaderFieldInt(HttpHeaders.CONTENT_LENGTH, 0) > MAX_IMAGE_SIZE) { log.info("Too large"); errorResponse(request, response, "badimage"); return; } log.info("Decoding " + imageURL); processStream(is, request, response); } finally { consumeRemainder(is); } } catch (IOException ioe) { log.info(ioe.toString()); errorResponse(request, response, "badurl"); } finally { connection.disconnect(); } }
From source file:org.jclouds.s3.filters.Aws4SignerForChunkedUpload.java
protected HttpRequest sign(HttpRequest request) throws HttpException { checkNotNull(request, "request is not ready to sign"); checkNotNull(request.getEndpoint(), "request is not ready to sign, request.endpoint not present."); Payload payload = request.getPayload(); // chunked upload required content-length. Long contentLength = payload.getContentMetadata().getContentLength(); // check contentLength not null checkNotNull(contentLength, "request is not ready to sign, payload contentLength not present."); // get host from request endpoint. String host = request.getEndpoint().getHost(); Date date = timestampProvider.get(); String timestamp = timestampFormat.format(date); String datestamp = dateFormat.format(date); String service = serviceAndRegion.service(); String region = serviceAndRegion.region(host); String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request"); HttpRequest.Builder<?> requestBuilder = request.toBuilder() // .removeHeader(AUTHORIZATION) // remove Authorization .removeHeader(DATE) // remove Date .removeHeader(CONTENT_LENGTH); // remove Content-Length ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap .<String, String>naturalOrder(); // content-encoding String contentEncoding = CONTENT_ENCODING_HEADER_AWS_CHUNKED; String originalContentEncoding = payload.getContentMetadata().getContentEncoding(); if (originalContentEncoding != null) { contentEncoding += "," + originalContentEncoding; }/*from w w w . j av a2 s . c om*/ requestBuilder.replaceHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding); signedHeadersBuilder.put(HttpHeaders.CONTENT_ENCODING.toLowerCase(), contentEncoding); // x-amz-decoded-content-length requestBuilder.replaceHeader(AMZ_DECODED_CONTENT_LENGTH_HEADER, contentLength.toString()); signedHeadersBuilder.put(AMZ_DECODED_CONTENT_LENGTH_HEADER.toLowerCase(), contentLength.toString()); // how big is the overall request stream going to be once we add the signature // 'headers' to each chunk? long totalLength = calculateChunkedContentLength(contentLength, userDataBlockSize); requestBuilder.replaceHeader(CONTENT_LENGTH, Long.toString(totalLength)); signedHeadersBuilder.put(CONTENT_LENGTH.toLowerCase(), Long.toString(totalLength)); // Content MD5 String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5); if (payload != null) { HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode(); if (md5 != null) { contentMD5 = BaseEncoding.base64().encode(md5.asBytes()); } } if (contentMD5 != null) { requestBuilder.replaceHeader(CONTENT_MD5, contentMD5); signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5); } // Content Type // content-type is not a required signing param. However, examples use this, so we include it to ease testing. String contentType = getContentType(request); if (!Strings.isNullOrEmpty(contentType)) { requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType); signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType); } else { requestBuilder.removeHeader(HttpHeaders.CONTENT_TYPE); } // host requestBuilder.replaceHeader(HttpHeaders.HOST, host); signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host); // user-agent, not a required signing param if (request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) { signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(), request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT)); } // all x-amz-* headers appendAmzHeaders(request, signedHeadersBuilder); // x-amz-security-token Credentials credentials = creds.get(); if (credentials instanceof SessionCredentials) { String token = SessionCredentials.class.cast(credentials).getSessionToken(); requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token); signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token); } // x-amz-content-sha256 String contentSha256 = getPayloadHash(); requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256); signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256); // put x-amz-date requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp); signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp); ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build(); String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders, timestamp, credentialScope, contentSha256); signatureWire.getWireLog().debug("<< " + stringToSign); byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service); // init hmacSHA256 processor for seed signature and chunked block signature ByteProcessor<byte[]> hmacSHA256; try { hmacSHA256 = hmacSHA256(crypto, signatureKey); } catch (InvalidKeyException e) { throw new ChunkedUploadException("invalid key", e); } // Calculating the Seed Signature String signature; try { signature = hex(readBytes(toInputStream(stringToSign), hmacSHA256)); } catch (IOException e) { throw new ChunkedUploadException("hmac sha256 seed signature error", e); } StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(" "); authorization.append("Credential=").append(Joiner.on("/").join(credentials.identity, credentialScope)) .append(", "); authorization.append("SignedHeaders=").append(Joiner.on(";").join(signedHeaders.keySet())).append(", "); authorization.append("Signature=").append(signature); // replace request payload with chunked upload payload ChunkedUploadPayload chunkedPayload = new ChunkedUploadPayload(payload, userDataBlockSize, timestamp, credentialScope, hmacSHA256, signature); chunkedPayload.getContentMetadata().setContentEncoding(null); return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString()) .payload(chunkedPayload).build(); }
From source file:io.mandrel.requests.http.ApacheHttpRequester.java
public HttpUriRequest prepareRequest(Uri uri, Spider spider) { Builder builder = RequestConfig.copy(defaultRequestConfig); HttpGet request = new HttpGet(uri.toURI()); // Add headers, cookies and ohter stuff if (strategy().headers() != null) { strategy().headers().forEach(header -> { if (header != null) { request.addHeader(header.getName(), header.getValue()); }// ww w.j a va 2s . co m }); } HttpParams params = new BasicHttpParams(); if (strategy().params() != null) { strategy().params().forEach(param -> { if (param != null) { params.setParameter(param.getName(), param.getValue()); } }); } request.setParams(params); // Configure the user -agent String userAgent = strategy().userAgentProvisionner().get(uri.toString(), spider); if (Strings.isNullOrEmpty(userAgent)) { request.addHeader(HttpHeaders.USER_AGENT, userAgent); } // Configure the proxy ProxyServer proxy = strategy().proxyServersSource().findProxy(spider); if (proxy != null) { // TODO Auth! HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol().getProtocol()); builder.setProxy(proxyHost); } request.setConfig(builder.build()); return request; }
From source file:org.fenixedu.bennu.oauth.servlets.OAuthAuthorizationServlet.java
private static String getDeviceId(HttpServletRequest request) { String deviceId = request.getParameter(DEVICE_ID); if (Strings.isNullOrEmpty(deviceId)) { return request.getHeader(HttpHeaders.USER_AGENT); }/* w w w . j a v a 2 s . com*/ return deviceId; }
From source file:com.ning.billing.recurly.RecurlyClient.java
private AsyncHttpClient.BoundRequestBuilder clientRequestBuilderCommon( AsyncHttpClient.BoundRequestBuilder requestBuilder) { return requestBuilder.addHeader("Authorization", "Basic " + key) .addHeader("X-Api-Version", RECURLY_API_VERSION).addHeader(HttpHeaders.USER_AGENT, userAgent) .setBodyEncoding("UTF-8"); }