本文整理了Java中okhttp3.Request
类的一些代码示例,展示了Request
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Request
类的具体详情如下:
包路径:okhttp3.Request
类名称:Request
[英]An HTTP request. Instances of this class are immutable if their #bodyis null or itself immutable.
[中]HTTP请求。如果此类的#body为null或自身不可变,则此类的实例是不可变的。
canonical example by Tabnine
public void sendGetRequest(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
String responseBody = response.body().string();
// ... do something with response
}
}
代码示例来源:origin: SonarSource/sonarqube
/**
* Inspired by https://github.com/square/okhttp/blob/parent-3.6.0/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L286
*/
private Response followPostRedirect(Response response) throws IOException {
String location = response.header("Location");
if (location == null) {
throw new IllegalStateException(format("Missing HTTP header 'Location' in redirect of %s", response.request().url()));
}
HttpUrl url = response.request().url().resolve(location);
// Don't follow redirects to unsupported protocols.
if (url == null) {
throw new IllegalStateException(format("Unsupported protocol in redirect of %s to %s", response.request().url(), location));
}
Request.Builder redirectRequest = response.request().newBuilder();
redirectRequest.post(response.request().body());
response.body().close();
return okHttpClient.newCall(redirectRequest.url(url).build()).execute();
}
代码示例来源:origin: square/okhttp
Entry(Response response) {
this.url = response.request().url().toString();
this.varyHeaders = HttpHeaders.varyHeaders(response);
this.requestMethod = response.request().method();
this.protocol = response.protocol();
this.code = response.code();
this.message = response.message();
this.responseHeaders = response.headers();
this.handshake = response.handshake();
this.sentRequestMillis = response.sentRequestAtMillis();
this.receivedResponseMillis = response.receivedResponseAtMillis();
}
代码示例来源:origin: square/okhttp
@Override public Response intercept(Chain chain) throws IOException {
long t1 = System.nanoTime();
Request request = chain.request();
logger.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
logger.info(String.format("Received response for %s in %.1fms%n%s",
request.url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
代码示例来源:origin: square/okhttp
CacheHttpURLConnection(Response response) {
super(response.request().url().url());
this.request = response.request();
this.response = response;
// Configure URLConnection inherited fields.
this.connected = true;
this.doOutput = request.body() != null;
this.doInput = true;
this.useCaches = true;
// Configure HttpUrlConnection inherited fields.
this.method = request.method();
}
代码示例来源:origin: square/okhttp
@Override public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build();
return chain.proceed(compressedRequest);
}
代码示例来源:origin: square/okhttp
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.url().host().equals(host)) {
request = request.newBuilder()
.header("Authorization", credentials)
.build();
}
return chain.proceed(request);
}
}
代码示例来源:origin: square/okhttp
public void fetch(HttpUrl url) throws IOException {
AtomicInteger previous = hostnames.putIfAbsent(url.host(), hostnameCount);
if (previous != null) hostnameCount = previous;
if (hostnameCount.incrementAndGet() > 100) return;
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
String responseSource = response.networkResponse() != null ? ("(network: "
+ response.networkResponse().code()
+ " over "
+ response.protocol()
Document document = Jsoup.parse(response.body().string(), url.toString());
for (Element element : document.select("a[href]")) {
String href = element.attr("href");
HttpUrl link = response.request().url().resolve(href);
if (link == null) continue; // URL is either invalid or its scheme isn't http/https.
queue.add(link.newBuilder().fragment(null).build());
代码示例来源:origin: prestodb/presto
public static <T> JsonResponse<T> execute(JsonCodec<T> codec, OkHttpClient client, Request request)
{
try (Response response = client.newCall(request).execute()) {
// TODO: fix in OkHttp: https://github.com/square/okhttp/issues/3111
if ((response.code() == 307) || (response.code() == 308)) {
String location = response.header(LOCATION);
if (location != null) {
request = request.newBuilder().url(location).build();
return execute(codec, client, request);
}
}
ResponseBody responseBody = requireNonNull(response.body());
String body = responseBody.string();
if (isJson(responseBody.contentType())) {
return new JsonResponse<>(response.code(), response.message(), response.headers(), body, codec);
}
return new JsonResponse<>(response.code(), response.message(), response.headers(), body);
}
catch (IOException e) {
// OkHttp throws this after clearing the interrupt status
// TODO: remove after updating to Okio 1.15.0+
if ((e instanceof InterruptedIOException) && "thread interrupted".equals(e.getMessage())) {
Thread.currentThread().interrupt();
}
throw new UncheckedIOException(e);
}
}
代码示例来源:origin: square/okhttp
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
Connection connection = chain.connection();
String requestStartMessage = "--> "
+ request.method()
+ ' ' + request.url()
+ (connection != null ? " " + connection.protocol() : "");
if (!logHeaders && hasRequestBody) {
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
logger.log("--> END " + request.method());
} else if (bodyHasUnknownEncoding(request.headers())) {
logger.log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
if (isPlaintext(buffer)) {
logger.log(buffer.readString(charset));
logger.log("--> END " + request.method()
+ " (" + requestBody.contentLength() + "-byte body)");
} else {
logger.log("--> END " + request.method() + " (binary "
+ requestBody.contentLength() + "-byte body omitted)");
ResponseBody responseBody = response.body();
代码示例来源:origin: JessYanCoding/MVPArms
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.body() != null && isParseable(request.body().contentType())) {
mPrinter.printJsonRequest(request, parseParams(request));
} else {
Response originalResponse;
try {
originalResponse = chain.proceed(request);
} catch (Exception e) {
Timber.w("Http Error: " + e);
ResponseBody responseBody = originalResponse.body();
if (responseBody != null && isParseable(responseBody.contentType())) {
bodyString = printResult(request, originalResponse, logResponse);
final List<String> segmentList = request.url().encodedPathSegments();
final String header = originalResponse.headers().toString();
final int code = originalResponse.code();
final boolean isSuccessful = originalResponse.isSuccessful();
final String message = originalResponse.message();
final String url = originalResponse.request().url().toString();
代码示例来源:origin: jeasonlzy/okhttp-OkGo
private Response logForResponse(Response response, long tookMs) {
Response.Builder builder = response.newBuilder();
Response clone = builder.build();
ResponseBody responseBody = clone.body();
boolean logBody = (printLevel == Level.BODY);
boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
log("<-- " + clone.code() + ' ' + clone.message() + ' ' + clone.request().url() + " (" + tookMs + "ms)");
if (logHeaders) {
Headers headers = clone.headers();
if (responseBody == null) return response;
if (isPlaintext(responseBody.contentType())) {
byte[] bytes = IOUtils.toByteArray(responseBody.byteStream());
MediaType contentType = responseBody.contentType();
String body = new String(bytes, getCharset(contentType));
log("\tbody:" + body);
代码示例来源:origin: square/okhttp
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
if (userRequest.header("Connection") == null) {
if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (userRequest.header("User-Agent") == null) {
Response networkResponse = chain.proceed(requestBuilder.build());
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
代码示例来源:origin: square/okhttp
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
httpCodec.flushRequest();
realChain.eventListener().responseHeadersStart(call);
if (request.body() instanceof DuplexRequestBody) {
((DuplexRequestBody) request.body()).foldSink(requestBodyOut);
} else {
long contentLength = request.body().contentLength();
CountingSink requestBodyOut =
new CountingSink(httpCodec.createRequestBody(request, contentLength));
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
realChain.eventListener().requestBodyEnd(call, requestBodyOut.successfulCount);
if (!(request.body() instanceof DuplexRequestBody)) {
httpCodec.finishRequest();
Response response = responseBuilder.build();
if ("close".equalsIgnoreCase(response.request().header("Connection"))
|| "close".equalsIgnoreCase(response.header("Connection"))) {
streamAllocation.noNewStreams();
代码示例来源:origin: square/okhttp
final String method = userResponse.request().method();
switch (responseCode) {
case HTTP_PROXY_AUTH:
Proxy selectedProxy = route != null
? route.proxy()
: client.proxy();
if (selectedProxy.type() != Proxy.Type.HTTP) {
throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
String location = userResponse.header("Location");
if (location == null) return null;
HttpUrl url = userResponse.request().url().resolve(location);
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
if (!sameScheme && !client.followSslRedirects()) return null;
Request.Builder requestBuilder = userResponse.request().newBuilder();
if (HttpMethod.permitsRequestBody(method)) {
final boolean maintainBody = HttpMethod.redirectsWithBody(method);
if (HttpMethod.redirectsToGet(method)) {
requestBuilder.method("GET", null);
} else {
RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
requestBuilder.method(method, requestBody);
if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
return null;
代码示例来源:origin: SonarSource/sonarqube
@Test
public void upload() throws IOException {
ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class);
settings.setProperty(SONAR_TELEMETRY_URL.getKey(), TELEMETRY_URL);
underTest.start();
underTest.upload(JSON);
verify(okHttpClient).newCall(requestCaptor.capture());
Request request = requestCaptor.getValue();
assertThat(request.method()).isEqualTo("POST");
assertThat(request.body().contentType()).isEqualTo(MediaType.parse("application/json; charset=utf-8"));
Buffer body = new Buffer();
request.body().writeTo(body);
assertThat(body.readUtf8()).isEqualTo(JSON);
assertThat(request.url().toString()).isEqualTo(TELEMETRY_URL);
}
代码示例来源:origin: Piasy/BigImageViewer
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
return response.newBuilder()
.body(new OkHttpProgressResponseBody(request.url(), response.body(),
listener))
.build();
}
};
代码示例来源:origin: square/okhttp
@Override public Response intercept(Chain chain) throws IOException {
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(504)
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
closeQuietly(cacheCandidate.body());
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
代码示例来源:origin: square/okhttp
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
closeQuietly(response.body());
if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release(true);
throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
if (!sameConnection(response, followUp.url())) {
streamAllocation.release(false);
streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(followUp.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
} else if (streamAllocation.codec() != null) {
代码示例来源:origin: square/okhttp
@Override public Request authenticate(Route route, Response response) throws IOException {
List<Challenge> challenges = response.challenges();
Request request = response.request();
HttpUrl url = request.url();
boolean proxyAuthorization = response.code() == 407;
Proxy proxy = route.proxy();
auth = java.net.Authenticator.requestPasswordAuthentication(
proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
url.scheme(), challenge.realm(), challenge.scheme(), url.url(),
RequestorType.PROXY);
} else {
auth = java.net.Authenticator.requestPasswordAuthentication(
url.host(), getConnectToInetAddress(proxy, url), url.port(), url.scheme(),
challenge.realm(), challenge.scheme(), url.url(), RequestorType.SERVER);
String credential = Credentials.basic(
auth.getUserName(), new String(auth.getPassword()), challenge.charset());
return request.newBuilder()
.header(proxyAuthorization ? "Proxy-Authorization" : "Authorization", credential)
.build();
内容来源于网络,如有侵权,请联系作者删除!