List of usage examples for com.squareup.okhttp HttpUrl host
String host
To view the source code for com.squareup.okhttp HttpUrl host.
Click Source Link
From source file:at.bitfire.dav4android.DavResource.java
License:Open Source License
private void parseMultiStatus_Response(XmlPullParser parser) throws IOException, XmlPullParserException, HttpException, UnsupportedDavException { /* <!ELEMENT response (href, ((href*, status)|(propstat+)), error?, responsedescription? , location?) > */ final int depth = parser.getDepth(); HttpUrl href = null; StatusLine status = null;//from w w w . j av a 2 s . c om PropertyCollection properties = new PropertyCollection(); int eventType = parser.getEventType(); while (!(eventType == XmlPullParser.END_TAG && parser.getDepth() == depth)) { if (eventType == XmlPullParser.START_TAG && parser.getDepth() == depth + 1) { String ns = parser.getNamespace(), name = parser.getName(); if (XmlUtils.NS_WEBDAV.equals(ns)) switch (name) { case "href": String sHref = parser.nextText(); if (!sHref.startsWith("/")) { /* According to RFC 4918 8.3 URL Handling, only absolute paths are allowed as relative URLs. However, some servers reply with relative paths. */ int firstColon = sHref.indexOf(':'); if (firstColon != -1) { /* There are some servers which return not only relative paths, but relative paths like "a:b.vcf", which would be interpreted as scheme: "a", scheme-specific part: "b.vcf" normally. For maximum compatibility, we prefix all relative paths which contain ":" (but not "://"), with "./" to allow resolving by HttpUrl. */ boolean hierarchical = false; try { if ("://".equals(sHref.substring(firstColon, firstColon + 3))) hierarchical = true; } catch (IndexOutOfBoundsException e) { // no "://" } if (!hierarchical) sHref = "./" + sHref; } } href = location.resolve(sHref); break; case "status": try { status = StatusLine.parse(parser.nextText()); } catch (ProtocolException e) { log.warn("Invalid status line, treating as 500 Server Error"); status = new StatusLine(Protocol.HTTP_1_1, 500, "Invalid status line"); } break; case "propstat": PropertyCollection prop = parseMultiStatus_PropStat(parser); if (prop != null) properties.merge(prop, false); break; case "location": throw new UnsupportedDavException("Redirected child resources are not supported yet"); } } eventType = parser.next(); } if (href == null) { log.warn("Ignoring <response> without valid <href>"); return; } // if we know this resource is a collection, make sure href has a trailing slash (for clarity and resolving relative paths) ResourceType type = (ResourceType) properties.get(ResourceType.NAME); if (type != null && type.types.contains(ResourceType.COLLECTION)) href = UrlUtils.withTrailingSlash(href); log.debug("Received <response> for " + href + ", status: " + status + ", properties: " + properties); if (status != null) // treat an HTTP error of a single response (i.e. requested resource or a member) like an HTTP error of the requested resource checkStatus(status); // Which resource does this <response> represent? DavResource target = null; if (UrlUtils.equals(UrlUtils.omitTrailingSlash(href), UrlUtils.omitTrailingSlash(location))) { // it's about ourselves target = this; } else if (location.scheme().equals(href.scheme()) && location.host().equals(href.host()) && location.port() == href.port()) { List<String> locationSegments = location.pathSegments(), hrefSegments = href.pathSegments(); // don't compare trailing slash segment ("") int nBasePathSegments = locationSegments.size(); if ("".equals(locationSegments.get(nBasePathSegments - 1))) nBasePathSegments--; /* example: locationSegments = [ "davCollection", "" ] nBasePathSegments = 1 hrefSegments = [ "davCollection", "aMember" ] */ if (hrefSegments.size() > nBasePathSegments) { boolean sameBasePath = true; for (int i = 0; i < nBasePathSegments; i++) { if (!locationSegments.get(i).equals(hrefSegments.get(i))) { sameBasePath = false; break; } } if (sameBasePath) members.add(target = new DavResource(log, httpClient, href)); } } // set properties for target if (target != null) target.properties.merge(properties, true); else log.warn("Received <response> not for self and not for member resource"); }
From source file:com.auth0.android.Auth0.java
License:Open Source License
private HttpUrl resolveConfiguration(@Nullable String configurationDomain, @NonNull HttpUrl domainUrl) { HttpUrl url = ensureValidUrl(configurationDomain); if (url == null) { final String host = domainUrl.host(); if (host.endsWith(DOT_AUTH0_DOT_COM)) { String[] parts = host.split("\\."); if (parts.length > 3) { url = HttpUrl.parse("https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM); } else { url = HttpUrl.parse(AUTH0_US_CDN_URL); }/*from www. ja v a 2s.c o m*/ } else { url = domainUrl; } } return url; }
From source file:com.auth0.Auth0.java
License:Open Source License
private String resolveConfiguration(String configurationDomain, String domainUrl) { String url = ensureUrlString(configurationDomain); if (configurationDomain == null && domainUrl != null) { final HttpUrl domainUri = HttpUrl.parse(domainUrl); final String host = domainUri.host(); if (host.endsWith(DOT_AUTH0_DOT_COM)) { String[] parts = host.split("\\."); if (parts.length > 3) { url = "https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM; } else { url = AUTH0_US_CDN_URL; }/*from ww w .j a v a 2 s . c o m*/ } else { url = domainUrl; } } return url; }
From source file:com.baidu.oped.apm.plugin.okhttp.interceptor.HttpEngineSendRequestMethodInterceptor.java
License:Apache License
private String getDestinationId(HttpUrl httpUrl) { if (httpUrl == null || httpUrl.host() == null) { return "UnknownHttpClient"; }/*w w w .j a v a2 s . c o m*/ if (httpUrl.port() == HttpUrl.defaultPort(httpUrl.scheme())) { return httpUrl.host(); } final StringBuilder sb = new StringBuilder(); sb.append(httpUrl.host()); sb.append(':'); sb.append(httpUrl.port()); return sb.toString(); }
From source file:com.codenote.tikal.example.client.HttpLoggingInterceptor.java
License:Apache License
private static String requestPath(HttpUrl url) { String domain = url.scheme() + "://" + url.host(); String path = url.encodedPath(); String query = url.encodedQuery(); return query != null ? domain.concat(path + '?' + query) : domain.concat(path); }
From source file:com.navercorp.pinpoint.plugin.okhttp.interceptor.RequestBuilderBuildMethodInterceptor.java
License:Apache License
private String getDestinationId(HttpUrl httpUrl) { if (httpUrl == null || httpUrl.host() == null) { return "UnknownHttpClient"; }/*from w w w.j a v a 2 s.c o m*/ if (httpUrl.port() <= 0 || httpUrl.port() == HttpUrl.defaultPort(httpUrl.scheme())) { return httpUrl.host(); } final StringBuilder sb = new StringBuilder(); sb.append(httpUrl.host()); sb.append(':'); sb.append(httpUrl.port()); return sb.toString(); }
From source file:com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineConnectMethodFromUserRequestInterceptor.java
License:Apache License
@Override protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {/* w ww . j a va 2 s .c o m*/ recorder.recordApi(methodDescriptor); recorder.recordServiceType(OkHttpConstants.OK_HTTP_CLIENT_INTERNAL); recorder.recordException(throwable); if (target instanceof UserRequestGetter) { final Request request = ((UserRequestGetter) target)._$PINPOINT$_getUserRequest(); if (request != null && request.httpUrl() != null) { final HttpUrl httpUrl = request.httpUrl(); final String hostAndPort = HostAndPort.toHostAndPortString(httpUrl.host(), httpUrl.port()); recorder.recordAttribute(AnnotationKey.HTTP_INTERNAL_DISPLAY, hostAndPort); } } }
From source file:com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.RequestBuilderBuildMethodInterceptor.java
License:Apache License
private String getDestinationId(HttpUrl httpUrl) { if (httpUrl == null || httpUrl.host() == null) { return "UnknownHttpClient"; }/*from ww w .j a va 2 s.c o m*/ final int port = EndPointUtils.getPort(httpUrl.port(), HttpUrl.defaultPort(httpUrl.scheme())); return HostAndPort.toHostAndPortString(httpUrl.host(), port); }
From source file:io.minio.MinioClient.java
License:Apache License
/** * Creates Minio client object using given endpoint, port, access key, secret key and secure option. * * </p><b>Example:</b><br> * <pre>{@code MinioClient minioClient = * new MinioClient("play.minio.io", 9000, "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", false); * }</pre>/*from ww w .j ava2 s. co m*/ * * @param endpoint Request endpoint. Endpoint is an URL, domain name, IPv4 or IPv6 address.<pre> * Valid endpoints: * * https://s3.amazonaws.com * * https://s3.amazonaws.com/ * * https://play.minio.io:9000 * * http://play.minio.io:9010/ * * localhost * * localhost.localdomain * * play.minio.io * * 127.0.0.1 * * 192.168.1.60 * * ::1</pre> * * @param port Valid port. It should be in between 1 and 65535. Unused if endpoint is an URL. * @param accessKey Access key to access service in endpoint. * @param secretKey Secret key to access service in endpoint. * @param secure If true, access endpoint using HTTPS else access it using HTTP. * * @see #MinioClient(String endpoint) * @see #MinioClient(URL url) * @see #MinioClient(String endpoint, String accessKey, String secretKey) * @see #MinioClient(URL url, String accessKey, String secretKey) * @see #MinioClient(String endpoint, int port, String accessKey, String secretKey) * @see #MinioClient(String endpoint, String accessKey, String secretKey, boolean secure) */ public MinioClient(String endpoint, int port, String accessKey, String secretKey, boolean secure) throws InvalidEndpointException, InvalidPortException { if (endpoint == null) { throw new InvalidEndpointException(NULL_STRING, "null endpoint"); } if (port < 0 || port > 65535) { throw new InvalidPortException(port, "port must be in range of 1 to 65535"); } HttpUrl url = HttpUrl.parse(endpoint); if (url != null) { if (!"/".equals(url.encodedPath())) { throw new InvalidEndpointException(endpoint, "no path allowed in endpoint"); } // treat Amazon S3 host as special case String amzHost = url.host(); if (amzHost.endsWith(AMAZONAWS_COM) && !amzHost.equals(S3_AMAZONAWS_COM)) { throw new InvalidEndpointException(endpoint, "for Amazon S3, host should be 's3.amazonaws.com' in endpoint"); } HttpUrl.Builder urlBuilder = url.newBuilder(); Scheme scheme = Scheme.HTTP; if (secure) { scheme = Scheme.HTTPS; } urlBuilder.scheme(scheme.toString()); if (port > 0) { urlBuilder.port(port); } this.baseUrl = urlBuilder.build(); this.accessKey = accessKey; this.secretKey = secretKey; return; } // endpoint may be a valid hostname, IPv4 or IPv6 address if (!this.isValidEndpoint(endpoint)) { throw new InvalidEndpointException(endpoint, "invalid host"); } // treat Amazon S3 host as special case if (endpoint.endsWith(AMAZONAWS_COM) && !endpoint.equals(S3_AMAZONAWS_COM)) { throw new InvalidEndpointException(endpoint, "for amazon S3, host should be 's3.amazonaws.com'"); } Scheme scheme = Scheme.HTTP; if (secure) { scheme = Scheme.HTTPS; } if (port == 0) { this.baseUrl = new HttpUrl.Builder().scheme(scheme.toString()).host(endpoint).build(); } else { this.baseUrl = new HttpUrl.Builder().scheme(scheme.toString()).host(endpoint).port(port).build(); } this.accessKey = accessKey; this.secretKey = secretKey; }
From source file:io.minio.MinioClient.java
License:Apache License
/** * Creates Request object for given request parameters. * * @param method HTTP method.//from w w w . jav a 2 s. c om * @param bucketName Bucket name. * @param objectName Object name in the bucket. * @param region Amazon S3 region of the bucket. * @param headerMap Map of HTTP headers for the request. * @param queryParamMap Map of HTTP query parameters of the request. * @param contentType Content type of the request body. * @param body HTTP request body. * @param length Length of HTTP request body. */ private Request createRequest(Method method, String bucketName, String objectName, String region, Map<String, String> headerMap, Map<String, String> queryParamMap, final String contentType, final Object body, final int length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException { if (bucketName == null && objectName != null) { throw new InvalidBucketNameException(NULL_STRING, "null bucket name for object '" + objectName + "'"); } HttpUrl.Builder urlBuilder = this.baseUrl.newBuilder(); if (bucketName != null) { checkBucketName(bucketName); String host = this.baseUrl.host(); if (host.equals(S3_AMAZONAWS_COM)) { // special case: handle s3.amazonaws.com separately if (region != null) { host = AwsS3Endpoints.INSTANCE.endpoint(region); } boolean usePathStyle = false; if (method == Method.PUT && objectName == null && queryParamMap == null) { // use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from s3.amazonaws.com usePathStyle = true; } else if (queryParamMap != null && queryParamMap.containsKey("location")) { // use path style for location query usePathStyle = true; } else if (bucketName.contains(".") && this.baseUrl.isHttps()) { // use path style where '.' in bucketName causes SSL certificate validation error usePathStyle = true; } if (usePathStyle) { urlBuilder.host(host); urlBuilder.addPathSegment(bucketName); } else { urlBuilder.host(bucketName + "." + host); } } else { urlBuilder.addPathSegment(bucketName); } } if (objectName != null) { for (String pathSegment : objectName.split("/")) { // Limitation: // 1. OkHttp does not allow to add '.' and '..' as path segment. // 2. Its not allowed to add path segment as '/', '//', '/usr' or 'usr/'. urlBuilder.addPathSegment(pathSegment); } } if (queryParamMap != null) { for (Map.Entry<String, String> entry : queryParamMap.entrySet()) { urlBuilder.addEncodedQueryParameter(Signer.encodeQueryString(entry.getKey()), Signer.encodeQueryString(entry.getValue())); } } RequestBody requestBody = null; if (body != null) { requestBody = new RequestBody() { @Override public MediaType contentType() { if (contentType != null) { return MediaType.parse(contentType); } else { return MediaType.parse("application/octet-stream"); } } @Override public long contentLength() { if (body instanceof InputStream || body instanceof RandomAccessFile || body instanceof byte[]) { return length; } if (length == 0) { return -1; } else { return length; } } @Override public void writeTo(BufferedSink sink) throws IOException { byte[] data = null; if (body instanceof InputStream) { InputStream stream = (InputStream) body; sink.write(Okio.source(stream), length); } else if (body instanceof RandomAccessFile) { RandomAccessFile file = (RandomAccessFile) body; sink.write(Okio.source(Channels.newInputStream(file.getChannel())), length); } else if (body instanceof byte[]) { sink.write(data, 0, length); } else { sink.writeUtf8(body.toString()); } } }; } HttpUrl url = urlBuilder.build(); // urlBuilder does not encode some characters properly for Amazon S3. // Encode such characters properly here. List<String> pathSegments = url.encodedPathSegments(); urlBuilder = url.newBuilder(); for (int i = 0; i < pathSegments.size(); i++) { urlBuilder.setEncodedPathSegment(i, pathSegments.get(i).replaceAll("\\!", "%21").replaceAll("\\$", "%24").replaceAll("\\&", "%26") .replaceAll("\\'", "%27").replaceAll("\\(", "%28").replaceAll("\\)", "%29") .replaceAll("\\*", "%2A").replaceAll("\\+", "%2B").replaceAll("\\,", "%2C") .replaceAll("\\:", "%3A").replaceAll("\\;", "%3B").replaceAll("\\=", "%3D") .replaceAll("\\@", "%40").replaceAll("\\[", "%5B").replaceAll("\\]", "%5D")); } url = urlBuilder.build(); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); requestBuilder.method(method.toString(), requestBody); if (headerMap != null) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { requestBuilder.header(entry.getKey(), entry.getValue()); } } String sha256Hash = null; String md5Hash = null; if (this.accessKey != null && this.secretKey != null) { // No need to compute sha256 if endpoint scheme is HTTPS. Issue #415. if (url.isHttps()) { sha256Hash = "UNSIGNED-PAYLOAD"; if (body instanceof BufferedInputStream) { md5Hash = Digest.md5Hash((BufferedInputStream) body, length); } else if (body instanceof RandomAccessFile) { md5Hash = Digest.md5Hash((RandomAccessFile) body, length); } else if (body instanceof byte[]) { byte[] data = (byte[]) body; md5Hash = Digest.md5Hash(data, length); } } else { if (body == null) { sha256Hash = Digest.sha256Hash(new byte[0]); } else { if (body instanceof BufferedInputStream) { String[] hashes = Digest.sha256md5Hashes((BufferedInputStream) body, length); sha256Hash = hashes[0]; md5Hash = hashes[1]; } else if (body instanceof RandomAccessFile) { String[] hashes = Digest.sha256md5Hashes((RandomAccessFile) body, length); sha256Hash = hashes[0]; md5Hash = hashes[1]; } else if (body instanceof byte[]) { byte[] data = (byte[]) body; sha256Hash = Digest.sha256Hash(data, length); md5Hash = Digest.md5Hash(data, length); } else { sha256Hash = Digest.sha256Hash(body.toString()); } } } } if (md5Hash != null) { requestBuilder.header("Content-MD5", md5Hash); } if (url.port() == 80 || url.port() == 443) { requestBuilder.header("Host", url.host()); } else { requestBuilder.header("Host", url.host() + ":" + url.port()); } requestBuilder.header("User-Agent", this.userAgent); if (sha256Hash != null) { requestBuilder.header("x-amz-content-sha256", sha256Hash); } DateTime date = new DateTime(); requestBuilder.header("x-amz-date", date.toString(DateFormat.AMZ_DATE_FORMAT)); return requestBuilder.build(); }