okhttp3.Request类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(15.0k)|赞(0)|评价(0)|浏览(446)

本文整理了Java中okhttp3.Request类的一些代码示例,展示了Request类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Request类的具体详情如下:
包路径:okhttp3.Request
类名称: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

  1. public void sendGetRequest(String url) throws IOException {
  2. OkHttpClient client = new OkHttpClient();
  3. Request request = new Request.Builder().url(url).build();
  4. try (Response response = client.newCall(request).execute()) {
  5. String responseBody = response.body().string();
  6. // ... do something with response
  7. }
  8. }

代码示例来源:origin: SonarSource/sonarqube

  1. /**
  2. * Inspired by https://github.com/square/okhttp/blob/parent-3.6.0/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L286
  3. */
  4. private Response followPostRedirect(Response response) throws IOException {
  5. String location = response.header("Location");
  6. if (location == null) {
  7. throw new IllegalStateException(format("Missing HTTP header 'Location' in redirect of %s", response.request().url()));
  8. }
  9. HttpUrl url = response.request().url().resolve(location);
  10. // Don't follow redirects to unsupported protocols.
  11. if (url == null) {
  12. throw new IllegalStateException(format("Unsupported protocol in redirect of %s to %s", response.request().url(), location));
  13. }
  14. Request.Builder redirectRequest = response.request().newBuilder();
  15. redirectRequest.post(response.request().body());
  16. response.body().close();
  17. return okHttpClient.newCall(redirectRequest.url(url).build()).execute();
  18. }

代码示例来源:origin: square/okhttp

  1. Entry(Response response) {
  2. this.url = response.request().url().toString();
  3. this.varyHeaders = HttpHeaders.varyHeaders(response);
  4. this.requestMethod = response.request().method();
  5. this.protocol = response.protocol();
  6. this.code = response.code();
  7. this.message = response.message();
  8. this.responseHeaders = response.headers();
  9. this.handshake = response.handshake();
  10. this.sentRequestMillis = response.sentRequestAtMillis();
  11. this.receivedResponseMillis = response.receivedResponseAtMillis();
  12. }

代码示例来源:origin: square/okhttp

  1. @Override public Response intercept(Chain chain) throws IOException {
  2. long t1 = System.nanoTime();
  3. Request request = chain.request();
  4. logger.info(String.format("Sending request %s on %s%n%s",
  5. request.url(), chain.connection(), request.headers()));
  6. Response response = chain.proceed(request);
  7. long t2 = System.nanoTime();
  8. logger.info(String.format("Received response for %s in %.1fms%n%s",
  9. request.url(), (t2 - t1) / 1e6d, response.headers()));
  10. return response;
  11. }
  12. }

代码示例来源:origin: square/okhttp

  1. CacheHttpURLConnection(Response response) {
  2. super(response.request().url().url());
  3. this.request = response.request();
  4. this.response = response;
  5. // Configure URLConnection inherited fields.
  6. this.connected = true;
  7. this.doOutput = request.body() != null;
  8. this.doInput = true;
  9. this.useCaches = true;
  10. // Configure HttpUrlConnection inherited fields.
  11. this.method = request.method();
  12. }

代码示例来源:origin: square/okhttp

  1. @Override public Response intercept(Chain chain) throws IOException {
  2. Request originalRequest = chain.request();
  3. if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
  4. return chain.proceed(originalRequest);
  5. }
  6. Request compressedRequest = originalRequest.newBuilder()
  7. .header("Content-Encoding", "gzip")
  8. .method(originalRequest.method(), gzip(originalRequest.body()))
  9. .build();
  10. return chain.proceed(compressedRequest);
  11. }

代码示例来源:origin: square/okhttp

  1. @Override public Response intercept(Chain chain) throws IOException {
  2. Request request = chain.request();
  3. if (request.url().host().equals(host)) {
  4. request = request.newBuilder()
  5. .header("Authorization", credentials)
  6. .build();
  7. }
  8. return chain.proceed(request);
  9. }
  10. }

代码示例来源:origin: square/okhttp

  1. public void fetch(HttpUrl url) throws IOException {
  2. AtomicInteger previous = hostnames.putIfAbsent(url.host(), hostnameCount);
  3. if (previous != null) hostnameCount = previous;
  4. if (hostnameCount.incrementAndGet() > 100) return;
  5. Request request = new Request.Builder()
  6. .url(url)
  7. .build();
  8. try (Response response = client.newCall(request).execute()) {
  9. String responseSource = response.networkResponse() != null ? ("(network: "
  10. + response.networkResponse().code()
  11. + " over "
  12. + response.protocol()
  13. Document document = Jsoup.parse(response.body().string(), url.toString());
  14. for (Element element : document.select("a[href]")) {
  15. String href = element.attr("href");
  16. HttpUrl link = response.request().url().resolve(href);
  17. if (link == null) continue; // URL is either invalid or its scheme isn't http/https.
  18. queue.add(link.newBuilder().fragment(null).build());

代码示例来源:origin: prestodb/presto

  1. public static <T> JsonResponse<T> execute(JsonCodec<T> codec, OkHttpClient client, Request request)
  2. {
  3. try (Response response = client.newCall(request).execute()) {
  4. // TODO: fix in OkHttp: https://github.com/square/okhttp/issues/3111
  5. if ((response.code() == 307) || (response.code() == 308)) {
  6. String location = response.header(LOCATION);
  7. if (location != null) {
  8. request = request.newBuilder().url(location).build();
  9. return execute(codec, client, request);
  10. }
  11. }
  12. ResponseBody responseBody = requireNonNull(response.body());
  13. String body = responseBody.string();
  14. if (isJson(responseBody.contentType())) {
  15. return new JsonResponse<>(response.code(), response.message(), response.headers(), body, codec);
  16. }
  17. return new JsonResponse<>(response.code(), response.message(), response.headers(), body);
  18. }
  19. catch (IOException e) {
  20. // OkHttp throws this after clearing the interrupt status
  21. // TODO: remove after updating to Okio 1.15.0+
  22. if ((e instanceof InterruptedIOException) && "thread interrupted".equals(e.getMessage())) {
  23. Thread.currentThread().interrupt();
  24. }
  25. throw new UncheckedIOException(e);
  26. }
  27. }

代码示例来源:origin: square/okhttp

  1. RequestBody requestBody = request.body();
  2. boolean hasRequestBody = requestBody != null;
  3. Connection connection = chain.connection();
  4. String requestStartMessage = "--> "
  5. + request.method()
  6. + ' ' + request.url()
  7. + (connection != null ? " " + connection.protocol() : "");
  8. if (!logHeaders && hasRequestBody) {
  9. Headers headers = request.headers();
  10. for (int i = 0, count = headers.size(); i < count; i++) {
  11. String name = headers.name(i);
  12. logger.log("--> END " + request.method());
  13. } else if (bodyHasUnknownEncoding(request.headers())) {
  14. logger.log("--> END " + request.method() + " (encoded body omitted)");
  15. } else {
  16. Buffer buffer = new Buffer();
  17. if (isPlaintext(buffer)) {
  18. logger.log(buffer.readString(charset));
  19. logger.log("--> END " + request.method()
  20. + " (" + requestBody.contentLength() + "-byte body)");
  21. } else {
  22. logger.log("--> END " + request.method() + " (binary "
  23. + requestBody.contentLength() + "-byte body omitted)");
  24. ResponseBody responseBody = response.body();

代码示例来源:origin: JessYanCoding/MVPArms

  1. @Override
  2. public Response intercept(Chain chain) throws IOException {
  3. Request request = chain.request();
  4. if (request.body() != null && isParseable(request.body().contentType())) {
  5. mPrinter.printJsonRequest(request, parseParams(request));
  6. } else {
  7. Response originalResponse;
  8. try {
  9. originalResponse = chain.proceed(request);
  10. } catch (Exception e) {
  11. Timber.w("Http Error: " + e);
  12. ResponseBody responseBody = originalResponse.body();
  13. if (responseBody != null && isParseable(responseBody.contentType())) {
  14. bodyString = printResult(request, originalResponse, logResponse);
  15. final List<String> segmentList = request.url().encodedPathSegments();
  16. final String header = originalResponse.headers().toString();
  17. final int code = originalResponse.code();
  18. final boolean isSuccessful = originalResponse.isSuccessful();
  19. final String message = originalResponse.message();
  20. final String url = originalResponse.request().url().toString();

代码示例来源:origin: jeasonlzy/okhttp-OkGo

  1. private Response logForResponse(Response response, long tookMs) {
  2. Response.Builder builder = response.newBuilder();
  3. Response clone = builder.build();
  4. ResponseBody responseBody = clone.body();
  5. boolean logBody = (printLevel == Level.BODY);
  6. boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
  7. log("<-- " + clone.code() + ' ' + clone.message() + ' ' + clone.request().url() + " (" + tookMs + "ms)");
  8. if (logHeaders) {
  9. Headers headers = clone.headers();
  10. if (responseBody == null) return response;
  11. if (isPlaintext(responseBody.contentType())) {
  12. byte[] bytes = IOUtils.toByteArray(responseBody.byteStream());
  13. MediaType contentType = responseBody.contentType();
  14. String body = new String(bytes, getCharset(contentType));
  15. log("\tbody:" + body);

代码示例来源:origin: square/okhttp

  1. @Override public Response intercept(Chain chain) throws IOException {
  2. Request userRequest = chain.request();
  3. Request.Builder requestBuilder = userRequest.newBuilder();
  4. RequestBody body = userRequest.body();
  5. if (body != null) {
  6. MediaType contentType = body.contentType();
  7. if (contentType != null) {
  8. requestBuilder.header("Content-Type", contentType.toString());
  9. requestBuilder.header("Content-Length", Long.toString(contentLength));
  10. requestBuilder.removeHeader("Transfer-Encoding");
  11. if (userRequest.header("Host") == null) {
  12. requestBuilder.header("Host", hostHeader(userRequest.url(), false));
  13. if (userRequest.header("Connection") == null) {
  14. if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
  15. List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
  16. if (userRequest.header("User-Agent") == null) {
  17. Response networkResponse = chain.proceed(requestBuilder.build());
  18. HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

代码示例来源:origin: square/okhttp

  1. if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
  2. if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
  3. httpCodec.flushRequest();
  4. realChain.eventListener().responseHeadersStart(call);
  5. if (request.body() instanceof DuplexRequestBody) {
  6. ((DuplexRequestBody) request.body()).foldSink(requestBodyOut);
  7. } else {
  8. long contentLength = request.body().contentLength();
  9. CountingSink requestBodyOut =
  10. new CountingSink(httpCodec.createRequestBody(request, contentLength));
  11. BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
  12. request.body().writeTo(bufferedRequestBody);
  13. bufferedRequestBody.close();
  14. realChain.eventListener().requestBodyEnd(call, requestBodyOut.successfulCount);
  15. if (!(request.body() instanceof DuplexRequestBody)) {
  16. httpCodec.finishRequest();
  17. Response response = responseBuilder.build();
  18. if ("close".equalsIgnoreCase(response.request().header("Connection"))
  19. || "close".equalsIgnoreCase(response.header("Connection"))) {
  20. streamAllocation.noNewStreams();

代码示例来源:origin: square/okhttp

  1. final String method = userResponse.request().method();
  2. switch (responseCode) {
  3. case HTTP_PROXY_AUTH:
  4. Proxy selectedProxy = route != null
  5. ? route.proxy()
  6. : client.proxy();
  7. if (selectedProxy.type() != Proxy.Type.HTTP) {
  8. throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
  9. String location = userResponse.header("Location");
  10. if (location == null) return null;
  11. HttpUrl url = userResponse.request().url().resolve(location);
  12. boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
  13. if (!sameScheme && !client.followSslRedirects()) return null;
  14. Request.Builder requestBuilder = userResponse.request().newBuilder();
  15. if (HttpMethod.permitsRequestBody(method)) {
  16. final boolean maintainBody = HttpMethod.redirectsWithBody(method);
  17. if (HttpMethod.redirectsToGet(method)) {
  18. requestBuilder.method("GET", null);
  19. } else {
  20. RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
  21. requestBuilder.method(method, requestBody);
  22. if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
  23. return null;

代码示例来源:origin: SonarSource/sonarqube

  1. @Test
  2. public void upload() throws IOException {
  3. ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class);
  4. settings.setProperty(SONAR_TELEMETRY_URL.getKey(), TELEMETRY_URL);
  5. underTest.start();
  6. underTest.upload(JSON);
  7. verify(okHttpClient).newCall(requestCaptor.capture());
  8. Request request = requestCaptor.getValue();
  9. assertThat(request.method()).isEqualTo("POST");
  10. assertThat(request.body().contentType()).isEqualTo(MediaType.parse("application/json; charset=utf-8"));
  11. Buffer body = new Buffer();
  12. request.body().writeTo(body);
  13. assertThat(body.readUtf8()).isEqualTo(JSON);
  14. assertThat(request.url().toString()).isEqualTo(TELEMETRY_URL);
  15. }

代码示例来源:origin: Piasy/BigImageViewer

  1. @Override
  2. public Response intercept(Chain chain) throws IOException {
  3. Request request = chain.request();
  4. Response response = chain.proceed(request);
  5. return response.newBuilder()
  6. .body(new OkHttpProgressResponseBody(request.url(), response.body(),
  7. listener))
  8. .build();
  9. }
  10. };

代码示例来源:origin: square/okhttp

  1. @Override public Response intercept(Chain chain) throws IOException {
  2. Response cacheCandidate = cache != null
  3. ? cache.get(chain.request())
  4. : null;
  5. CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
  6. Request networkRequest = strategy.networkRequest;
  7. Response cacheResponse = strategy.cacheResponse;
  8. closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
  9. .request(chain.request())
  10. .protocol(Protocol.HTTP_1_1)
  11. .code(504)
  12. return cacheResponse.newBuilder()
  13. .cacheResponse(stripBody(cacheResponse))
  14. .build();
  15. closeQuietly(cacheCandidate.body());
  16. .networkResponse(stripBody(networkResponse))
  17. .build();
  18. networkResponse.body().close();
  19. if (HttpMethod.invalidatesCache(networkRequest.method())) {
  20. try {
  21. cache.remove(networkRequest);

代码示例来源:origin: square/okhttp

  1. @Override public Response intercept(Chain chain) throws IOException {
  2. Request request = chain.request();
  3. RealInterceptorChain realChain = (RealInterceptorChain) chain;
  4. Call call = realChain.call();
  5. EventListener eventListener = realChain.eventListener();
  6. StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
  7. createAddress(request.url()), call, eventListener, callStackTrace);
  8. this.streamAllocation = streamAllocation;
  9. response = response.newBuilder()
  10. .priorResponse(priorResponse.newBuilder()
  11. .body(null)
  12. .build())
  13. closeQuietly(response.body());
  14. if (followUp.body() instanceof UnrepeatableRequestBody) {
  15. streamAllocation.release(true);
  16. throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
  17. if (!sameConnection(response, followUp.url())) {
  18. streamAllocation.release(false);
  19. streamAllocation = new StreamAllocation(client.connectionPool(),
  20. createAddress(followUp.url()), call, eventListener, callStackTrace);
  21. this.streamAllocation = streamAllocation;
  22. } else if (streamAllocation.codec() != null) {

代码示例来源:origin: square/okhttp

  1. @Override public Request authenticate(Route route, Response response) throws IOException {
  2. List<Challenge> challenges = response.challenges();
  3. Request request = response.request();
  4. HttpUrl url = request.url();
  5. boolean proxyAuthorization = response.code() == 407;
  6. Proxy proxy = route.proxy();
  7. auth = java.net.Authenticator.requestPasswordAuthentication(
  8. proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
  9. url.scheme(), challenge.realm(), challenge.scheme(), url.url(),
  10. RequestorType.PROXY);
  11. } else {
  12. auth = java.net.Authenticator.requestPasswordAuthentication(
  13. url.host(), getConnectToInetAddress(proxy, url), url.port(), url.scheme(),
  14. challenge.realm(), challenge.scheme(), url.url(), RequestorType.SERVER);
  15. String credential = Credentials.basic(
  16. auth.getUserName(), new String(auth.getPassword()), challenge.charset());
  17. return request.newBuilder()
  18. .header(proxyAuthorization ? "Proxy-Authorization" : "Authorization", credential)
  19. .build();

相关文章