本文整理汇总了Java中okhttp3.internal.Util类的典型用法代码示例。如果您正苦于以下问题:Java Util类的具体用法?Java Util怎么用?Java Util使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Util类属于okhttp3.internal包,在下文中一共展示了Util类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: Address
import okhttp3.internal.Util; //导入依赖的package包/类
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier,
CertificatePinner certificatePinner, Authenticator proxyAuthenticator, Proxy proxy,
List<Protocol> protocols, List<ConnectionSpec> connectionSpecs, ProxySelector proxySelector) {
this.url = new HttpUrl.Builder()
.scheme(sslSocketFactory != null ? "https" : "http")
.host(uriHost)
.port(uriPort)
.build();
if (dns == null) throw new NullPointerException("dns == null");
this.dns = dns;
if (socketFactory == null) throw new NullPointerException("socketFactory == null");
this.socketFactory = socketFactory;
if (proxyAuthenticator == null) {
throw new NullPointerException("proxyAuthenticator == null");
}
this.proxyAuthenticator = proxyAuthenticator;
if (protocols == null) throw new NullPointerException("protocols == null");
this.protocols = Util.immutableList(protocols);
if (connectionSpecs == null) throw new NullPointerException("connectionSpecs == null");
this.connectionSpecs = Util.immutableList(connectionSpecs);
if (proxySelector == null) throw new NullPointerException("proxySelector == null");
this.proxySelector = proxySelector;
this.proxy = proxy;
this.sslSocketFactory = sslSocketFactory;
this.hostnameVerifier = hostnameVerifier;
this.certificatePinner = certificatePinner;
}
示例2: createOkRequest
import okhttp3.internal.Util; //导入依赖的package包/类
/**
* Creates an OkHttp {@link Request} from the supplied information.
*
* <p>This method allows a {@code null} value for {@code requestHeaders} for situations where a
* connection is already connected and access to the headers has been lost. See {@link
* java.net.HttpURLConnection#getRequestProperties()} for details.
*/
public static Request createOkRequest(
URI uri, String requestMethod, Map<String, List<String>> requestHeaders) {
// OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod)
? Util.EMPTY_REQUEST
: null;
Request.Builder builder = new Request.Builder()
.url(uri.toString())
.method(requestMethod, placeholderBody);
if (requestHeaders != null) {
Headers headers = extractOkHeaders(requestHeaders, null);
builder.headers(headers);
}
return builder.build();
}
示例3: serverMessageLengthShort
import okhttp3.internal.Util; //导入依赖的package包/类
@Test public void serverMessageLengthShort() throws IOException {
Sink sink = serverWriter.newMessageSink(OPCODE_BINARY, -1);
// Create a payload which will overflow the normal payload byte size.
Buffer payload = new Buffer();
while (payload.completeSegmentByteCount() <= PAYLOAD_BYTE_MAX) {
payload.writeByte('0');
}
long byteCount = payload.completeSegmentByteCount();
// Write directly to the unbuffered sink. This ensures it will become single frame.
sink.write(payload.clone(), byteCount);
assertData("027e"); // 'e' == 4-byte follow-up length.
assertData(Util.format("%04X", payload.completeSegmentByteCount()));
assertData(payload.readByteArray());
sink.close();
assertData("8000");
}
示例4: enableHttp2FrameLogging
import okhttp3.internal.Util; //导入依赖的package包/类
private static void enableHttp2FrameLogging() {
frameLogger = Logger.getLogger(Http2.class.getName());
frameLogger.setLevel(Level.FINE);
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.FINE);
handler.setFormatter(new SimpleFormatter() {
@Override public String format(LogRecord record) {
return Util.format("%s%n", record.getMessage());
}
});
frameLogger.addHandler(handler);
}
示例5: create
import okhttp3.internal.Util; //导入依赖的package包/类
/** Returns a new request body that transmits {@code content}. */
public static RequestBody create(final MediaType contentType, final byte[] content,
final int offset, final int byteCount) {
if (content == null) throw new NullPointerException("content == null");
Util.checkOffsetAndCount(content.length, offset, byteCount);
return new RequestBody() {
@Override public MediaType contentType() {
return contentType;
}
@Override public long contentLength() {
return byteCount;
}
@Override public void writeTo(BufferedSink sink) throws IOException {
sink.write(content, offset, byteCount);
}
};
}
示例6: create
import okhttp3.internal.Util; //导入依赖的package包/类
/**
* Create a cache which will reside in {@code directory}. This cache is lazily initialized on
* first access and will be created if it does not exist.
*
* @param directory a writable directory
* @param valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store
*/
public static DiskLruCache create(FileSystem fileSystem, File directory, int appVersion,
int valueCount, long maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
if (valueCount <= 0) {
throw new IllegalArgumentException("valueCount <= 0");
}
// Use a single background thread to evict entries.
Executor executor = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp DiskLruCache", true));
return new DiskLruCache(fileSystem, directory, appVersion, valueCount, maxSize, executor);
}
示例7: initReaderAndWriter
import okhttp3.internal.Util; //导入依赖的package包/类
public void initReaderAndWriter(
String name, long pingIntervalMillis, Streams streams) throws IOException {
synchronized (this) {
this.streams = streams;
this.writer = new WebSocketWriter(streams.client, streams.sink, random);
this.executor = new ScheduledThreadPoolExecutor(1, Util.threadFactory(name, false));
if (pingIntervalMillis != 0) {
executor.scheduleAtFixedRate(
new PingRunnable(), pingIntervalMillis, pingIntervalMillis, MILLISECONDS);
}
if (!messageAndCloseQueue.isEmpty()) {
runWriter(); // Send messages that were enqueued before we were connected.
}
}
reader = new WebSocketReader(streams.client, streams.source, this);
}
示例8: shutdown
import okhttp3.internal.Util; //导入依赖的package包/类
/**
* Degrades this connection such that new streams can neither be created locally, nor accepted
* from the remote peer. Existing streams are not impacted. This is intended to permit an endpoint
* to gracefully stop accepting new requests without harming previously established streams.
*/
public void shutdown(ErrorCode statusCode) throws IOException {
synchronized (writer) {
int lastGoodStreamId;
synchronized (this) {
if (shutdown) {
return;
}
shutdown = true;
lastGoodStreamId = this.lastGoodStreamId;
}
// TODO: propagate exception message into debugData.
// TODO: configure a timeout on the reader so that it doesn’t block forever.
writer.goAway(lastGoodStreamId, statusCode, Util.EMPTY_BYTE_ARRAY);
}
}
示例9: execute
import okhttp3.internal.Util; //导入依赖的package包/类
@Override protected void execute() {
ErrorCode connectionErrorCode = ErrorCode.INTERNAL_ERROR;
ErrorCode streamErrorCode = ErrorCode.INTERNAL_ERROR;
try {
reader.readConnectionPreface(this);
while (reader.nextFrame(false, this)) {
}
connectionErrorCode = ErrorCode.NO_ERROR;
streamErrorCode = ErrorCode.CANCEL;
} catch (IOException e) {
connectionErrorCode = ErrorCode.PROTOCOL_ERROR;
streamErrorCode = ErrorCode.PROTOCOL_ERROR;
} finally {
try {
close(connectionErrorCode, streamErrorCode);
} catch (IOException ignored) {
}
Util.closeQuietly(reader);
}
}
示例10: supportedSpec
import okhttp3.internal.Util; //导入依赖的package包/类
/**
* Returns a copy of this that omits cipher suites and TLS versions not enabled by {@code
* sslSocket}.
*/
private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) {
String[] cipherSuitesIntersection = cipherSuites != null
? intersect(CipherSuite.ORDER_BY_NAME, sslSocket.getEnabledCipherSuites(), cipherSuites)
: sslSocket.getEnabledCipherSuites();
String[] tlsVersionsIntersection = tlsVersions != null
? intersect(Util.NATURAL_ORDER, sslSocket.getEnabledProtocols(), tlsVersions)
: sslSocket.getEnabledProtocols();
// In accordance with https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
// the SCSV cipher is added to signal that a protocol fallback has taken place.
String[] supportedCipherSuites = sslSocket.getSupportedCipherSuites();
int indexOfFallbackScsv = indexOf(
CipherSuite.ORDER_BY_NAME, supportedCipherSuites, "TLS_FALLBACK_SCSV");
if (isFallback && indexOfFallbackScsv != -1) {
cipherSuitesIntersection = concat(
cipherSuitesIntersection, supportedCipherSuites[indexOfFallbackScsv]);
}
return new Builder(this)
.cipherSuites(cipherSuitesIntersection)
.tlsVersions(tlsVersionsIntersection)
.build();
}
示例11: isCompatible
import okhttp3.internal.Util; //导入依赖的package包/类
/**
* Returns {@code true} if the socket, as currently configured, supports this connection spec. In
* order for a socket to be compatible the enabled cipher suites and protocols must intersect.
*
* <p>For cipher suites, at least one of the {@link #cipherSuites() required cipher suites} must
* match the socket's enabled cipher suites. If there are no required cipher suites the socket
* must have at least one cipher suite enabled.
*
* <p>For protocols, at least one of the {@link #tlsVersions() required protocols} must match the
* socket's enabled protocols.
*/
public boolean isCompatible(SSLSocket socket) {
if (!tls) {
return false;
}
if (tlsVersions != null && !nonEmptyIntersection(
Util.NATURAL_ORDER, tlsVersions, socket.getEnabledProtocols())) {
return false;
}
if (cipherSuites != null && !nonEmptyIntersection(
CipherSuite.ORDER_BY_NAME, cipherSuites, socket.getEnabledCipherSuites())) {
return false;
}
return true;
}
示例12: noDefaultContentLengthOnStreamingPost
import okhttp3.internal.Util; //导入依赖的package包/类
@Test public void noDefaultContentLengthOnStreamingPost() throws Exception {
final byte[] postBytes = "FGHIJ".getBytes(Util.UTF_8);
server.enqueue(new MockResponse().setBody("ABCDE"));
Call call = client.newCall(new Request.Builder()
.url(server.url("/foo"))
.post(new RequestBody() {
@Override public MediaType contentType() {
return MediaType.parse("text/plain; charset=utf-8");
}
@Override public void writeTo(BufferedSink sink) throws IOException {
sink.write(postBytes);
}
})
.build());
Response response = call.execute();
assertEquals("ABCDE", response.body().string());
RecordedRequest request = server.takeRequest();
assertEquals("POST /foo HTTP/1.1", request.getRequestLine());
assertArrayEquals(postBytes, request.getBody().readByteArray());
assertNull(request.getHeader("Content-Length"));
}
示例13: testUri
import okhttp3.internal.Util; //导入依赖的package包/类
private void testUri(
int codePoint, Encoding encoding, Component component, boolean uriEscaped) {
String string = new String(new int[] {codePoint}, 0, 1);
String encoded = encoding.encode(codePoint);
HttpUrl httpUrl = HttpUrl.parse(component.urlString(encoded));
URI uri = httpUrl.uri();
HttpUrl toAndFromUri = HttpUrl.get(uri);
if (uriEscaped) {
// The URI has more escaping than the HttpURL. Check that the decoded values still match.
if (uri.toString().equals(httpUrl.toString())) {
fail(Util.format("Encoding %s %#x using %s", component, codePoint, encoding));
}
if (!component.get(toAndFromUri).equals(string)) {
fail(Util.format("Encoding %s %#x using %s", component, codePoint, encoding));
}
} else {
// Check that the URI and HttpURL have the exact same escaping.
if (!toAndFromUri.equals(httpUrl)) {
fail(Util.format("Encoding %s %#x using %s", component, codePoint, encoding));
}
if (!uri.toString().equals(httpUrl.toString())) {
fail(Util.format("Encoding %s %#x using %s", component, codePoint, encoding));
}
}
}
示例14: get
import okhttp3.internal.Util; //导入依赖的package包/类
public static Handshake get(SSLSession session) {
String cipherSuiteString = session.getCipherSuite();
if (cipherSuiteString == null) throw new IllegalStateException("cipherSuite == null");
CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);
String tlsVersionString = session.getProtocol();
if (tlsVersionString == null) throw new IllegalStateException("tlsVersion == null");
TlsVersion tlsVersion = TlsVersion.forJavaName(tlsVersionString);
Certificate[] peerCertificates;
try {
peerCertificates = session.getPeerCertificates();
} catch (SSLPeerUnverifiedException ignored) {
peerCertificates = null;
}
List<Certificate> peerCertificatesList = peerCertificates != null
? Util.immutableList(peerCertificates)
: Collections.<Certificate>emptyList();
Certificate[] localCertificates = session.getLocalCertificates();
List<Certificate> localCertificatesList = localCertificates != null
? Util.immutableList(localCertificates)
: Collections.<Certificate>emptyList();
return new Handshake(tlsVersion, cipherSuite, peerCertificatesList, localCertificatesList);
}
示例15: goAwayWithoutDebugDataRoundTrip
import okhttp3.internal.Util; //导入依赖的package包/类
@Test public void goAwayWithoutDebugDataRoundTrip() throws IOException {
final ErrorCode expectedError = ErrorCode.PROTOCOL_ERROR;
writeMedium(frame, 8); // Without debug data there's only 2 32-bit fields.
frame.writeByte(Http2.TYPE_GOAWAY);
frame.writeByte(Http2.FLAG_NONE);
frame.writeInt(0); // connection-scope
frame.writeInt(expectedStreamId); // last good stream.
frame.writeInt(expectedError.httpCode);
// Check writer sends the same bytes.
assertEquals(frame, sendGoAway(expectedStreamId, expectedError, Util.EMPTY_BYTE_ARRAY));
reader.nextFrame(false, new BaseTestHandler() {
@Override public void goAway(
int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
assertEquals(expectedStreamId, lastGoodStreamId);
assertEquals(expectedError, errorCode);
assertEquals(0, debugData.size());
}
});
}