Search in sources :

Example 36 with Protocol

use of okhttp3.Protocol in project buck by facebook.

the class ThriftArtifactCache method storeImpl.

@Override
protected void storeImpl(final ArtifactInfo info, final Path file, final HttpArtifactCacheEvent.Finished.Builder eventBuilder) throws IOException {
    final ByteSource artifact = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return projectFilesystem.newFileInputStream(file);
        }
    };
    BuckCacheStoreRequest storeRequest = new BuckCacheStoreRequest();
    ArtifactMetadata artifactMetadata = infoToMetadata(info, artifact, repository, scheduleType, distributedBuildModeEnabled);
    storeRequest.setMetadata(artifactMetadata);
    PayloadInfo payloadInfo = new PayloadInfo();
    long artifactSizeBytes = artifact.size();
    payloadInfo.setSizeBytes(artifactSizeBytes);
    BuckCacheRequest cacheRequest = new BuckCacheRequest();
    cacheRequest.addToPayloads(payloadInfo);
    cacheRequest.setType(BuckCacheRequestType.STORE);
    cacheRequest.setStoreRequest(storeRequest);
    if (LOG.isVerboseEnabled()) {
        LOG.verbose(String.format("Storing artifact with metadata: [%s].", ThriftUtil.thriftToDebugJson(artifactMetadata)));
    }
    final ThriftArtifactCacheProtocol.Request request = ThriftArtifactCacheProtocol.createRequest(PROTOCOL, cacheRequest, artifact);
    Request.Builder builder = toOkHttpRequest(request);
    eventBuilder.getStoreBuilder().setRequestSizeBytes(request.getRequestLengthBytes());
    try (HttpResponse httpResponse = storeClient.makeRequest(hybridThriftEndpoint, builder)) {
        if (httpResponse.statusCode() != 200) {
            throw new IOException(String.format("Failed to store cache artifact with HTTP status code [%d:%s] " + " to url [%s] for build target [%s] that has size [%d] bytes.", httpResponse.statusCode(), httpResponse.statusMessage(), httpResponse.requestUrl(), info.getBuildTarget().orElse(null), artifactSizeBytes));
        }
        try (ThriftArtifactCacheProtocol.Response response = ThriftArtifactCacheProtocol.parseResponse(PROTOCOL, httpResponse.getBody())) {
            BuckCacheResponse cacheResponse = response.getThriftData();
            if (!cacheResponse.isWasSuccessful()) {
                reportFailure("Failed to store artifact with thriftErrorMessage=[%s] " + "url=[%s] artifactSizeBytes=[%d]", response.getThriftData().getErrorMessage(), httpResponse.requestUrl(), artifactSizeBytes);
            }
            eventBuilder.getStoreBuilder().setArtifactContentHash(storeRequest.getMetadata().artifactPayloadMd5);
            eventBuilder.getStoreBuilder().setWasStoreSuccessful(cacheResponse.isWasSuccessful());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Debug info for cache store request: artifactMetadata=[%s] response=[%s]", ThriftUtil.thriftToDebugJson(artifactMetadata), ThriftUtil.thriftToDebugJson(cacheResponse));
            }
        }
    }
}
Also used : BuckCacheStoreRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheStoreRequest) Request(okhttp3.Request) BuckCacheRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheRequest) BuckCacheFetchRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheFetchRequest) HttpResponse(com.facebook.buck.slb.HttpResponse) BuckCacheRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheRequest) IOException(java.io.IOException) ByteSource(com.google.common.io.ByteSource) BuckCacheStoreRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheStoreRequest) PayloadInfo(com.facebook.buck.artifact_cache.thrift.PayloadInfo) ArtifactMetadata(com.facebook.buck.artifact_cache.thrift.ArtifactMetadata) BuckCacheResponse(com.facebook.buck.artifact_cache.thrift.BuckCacheResponse)

Example 37 with Protocol

use of okhttp3.Protocol in project okhttp-OkGo by jeasonlzy.

the class HttpLoggingInterceptor method logForRequest.

private void logForRequest(Request request, Connection connection) throws IOException {
    boolean logBody = (printLevel == Level.BODY);
    boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    try {
        String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
        log(requestStartMessage);
        if (logHeaders) {
            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                log("\t" + headers.name(i) + ": " + headers.value(i));
            }
            log(" ");
            if (logBody && hasRequestBody) {
                if (isPlaintext(requestBody.contentType())) {
                    bodyToString(request);
                } else {
                    log("\tbody: maybe [file part] , too large too print , ignored!");
                }
            }
        }
    } catch (Exception e) {
        OkLogger.e(e);
    } finally {
        log("--> END " + request.method());
    }
}
Also used : HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Protocol(okhttp3.Protocol) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 38 with Protocol

use of okhttp3.Protocol in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClientTest method testGetParseResponse.

@Test
public void testGetParseResponse() throws IOException {
    int statusCode = 200;
    String reasonPhrase = "test reason";
    final String content = "test";
    final int contentLength = content.length();
    final String contentType = "application/json";
    String url = "http://www.parse.com/";
    Request request = new Request.Builder().url(url).build();
    Response okHttpResponse = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(statusCode).message(reasonPhrase).body(new ResponseBody() {

        @Override
        public MediaType contentType() {
            return MediaType.parse(contentType);
        }

        @Override
        public long contentLength() {
            return contentLength;
        }

        @Override
        public BufferedSource source() {
            Buffer buffer = new Buffer();
            buffer.write(content.getBytes());
            return buffer;
        }
    }).build();
    ParseOkHttpClient parseClient = new ParseOkHttpClient(10000, null);
    ParseHttpResponse parseResponse = parseClient.getResponse(okHttpResponse);
    // Verify status code
    assertEquals(statusCode, parseResponse.getStatusCode());
    // Verify reason phrase
    assertEquals(reasonPhrase, parseResponse.getReasonPhrase());
    // Verify content length
    assertEquals(contentLength, parseResponse.getTotalSize());
    // Verify content
    assertArrayEquals(content.getBytes(), ParseIOUtils.toByteArray(parseResponse.getContent()));
}
Also used : Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) ParseHttpResponse(com.parse.http.ParseHttpResponse) Buffer(okio.Buffer) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ResponseBody(okhttp3.ResponseBody) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 39 with Protocol

use of okhttp3.Protocol in project sonarqube by SonarSource.

the class WebhookCallerImpl method followPostRedirect.

/**
   * 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();
}
Also used : Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl)

Example 40 with Protocol

use of okhttp3.Protocol in project okhttp by square.

the class JavaApiConverterTest method createJavaCacheResponse_httpPost.

@Test
public void createJavaCacheResponse_httpPost() throws Exception {
    Request okRequest = createArbitraryOkRequest().newBuilder().url("http://insecure/request").post(createRequestBody("RequestBody")).build();
    ResponseBody responseBody = createResponseBody("ResponseBody");
    Response okResponse = createArbitraryOkResponse(okRequest).newBuilder().protocol(Protocol.HTTP_1_1).code(200).message("Fantastic").addHeader("key1", "value1_1").addHeader("key2", "value2").addHeader("key1", "value1_2").body(responseBody).build();
    CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse);
    assertFalse(javaCacheResponse instanceof SecureCacheResponse);
    Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders();
    assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1"));
    assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null));
    assertEquals("ResponseBody", readAll(javaCacheResponse.getBody()));
}
Also used : CacheResponse(java.net.CacheResponse) Response(okhttp3.Response) SecureCacheResponse(java.net.SecureCacheResponse) CacheResponse(java.net.CacheResponse) SecureCacheResponse(java.net.SecureCacheResponse) SecureCacheResponse(java.net.SecureCacheResponse) Request(okhttp3.Request) List(java.util.List) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Aggregations

Request (okhttp3.Request)26 Response (okhttp3.Response)26 Test (org.junit.Test)25 ResponseBody (okhttp3.ResponseBody)20 IOException (java.io.IOException)18 Protocol (okhttp3.Protocol)14 Buffer (okio.Buffer)13 HttpResponse (com.facebook.buck.slb.HttpResponse)12 LazyPath (com.facebook.buck.io.LazyPath)11 RuleKey (com.facebook.buck.rules.RuleKey)11 Path (java.nio.file.Path)11 OkHttpResponseWrapper (com.facebook.buck.slb.OkHttpResponseWrapper)10 List (java.util.List)10 MediaType (okhttp3.MediaType)10 FakeProjectFilesystem (com.facebook.buck.testutil.FakeProjectFilesystem)9 HttpURLConnection (java.net.HttpURLConnection)9 MockResponse (okhttp3.mockwebserver.MockResponse)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 DataOutputStream (java.io.DataOutputStream)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7