Search in sources :

Example 26 with Response

use of retrofit2.Response in project okhttp by square.

the class RealWebSocket method connect.

public void connect(OkHttpClient client) {
    client = client.newBuilder().protocols(ONLY_HTTP1).build();
    final int pingIntervalMillis = client.pingIntervalMillis();
    final Request request = originalRequest.newBuilder().header("Upgrade", "websocket").header("Connection", "Upgrade").header("Sec-WebSocket-Key", key).header("Sec-WebSocket-Version", "13").build();
    call = Internal.instance.newWebSocketCall(client, request);
    call.enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) {
            try {
                checkResponse(response);
            } catch (ProtocolException e) {
                failWebSocket(e, response);
                closeQuietly(response);
                return;
            }
            // Promote the HTTP streams into web socket streams.
            StreamAllocation streamAllocation = Internal.instance.streamAllocation(call);
            // Prevent connection pooling!
            streamAllocation.noNewStreams();
            Streams streams = streamAllocation.connection().newWebSocketStreams(streamAllocation);
            // Process all web socket messages.
            try {
                listener.onOpen(RealWebSocket.this, response);
                String name = "OkHttp WebSocket " + request.url().redact();
                initReaderAndWriter(name, pingIntervalMillis, streams);
                streamAllocation.connection().socket().setSoTimeout(0);
                loopReader();
            } catch (Exception e) {
                failWebSocket(e, null);
            }
        }

        @Override
        public void onFailure(Call call, IOException e) {
            failWebSocket(e, null);
        }
    });
}
Also used : Response(okhttp3.Response) StreamAllocation(okhttp3.internal.connection.StreamAllocation) Call(okhttp3.Call) ProtocolException(java.net.ProtocolException) Callback(okhttp3.Callback) Request(okhttp3.Request) ByteString(okio.ByteString) IOException(java.io.IOException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException)

Example 27 with Response

use of retrofit2.Response in project okhttp by square.

the class BridgeInterceptor method intercept.

@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());
        }
        long contentLength = body.contentLength();
        if (contentLength != -1) {
            requestBuilder.header("Content-Length", Long.toString(contentLength));
            requestBuilder.removeHeader("Transfer-Encoding");
        } else {
            requestBuilder.header("Transfer-Encoding", "chunked");
            requestBuilder.removeHeader("Content-Length");
        }
    }
    if (userRequest.header("Host") == null) {
        requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }
    if (userRequest.header("Connection") == null) {
        requestBuilder.header("Connection", "Keep-Alive");
    }
    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
        transparentGzip = true;
        requestBuilder.header("Accept-Encoding", "gzip");
    }
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
        requestBuilder.header("Cookie", cookieHeader(cookies));
    }
    if (userRequest.header("User-Agent") == null) {
        requestBuilder.header("User-Agent", Version.userAgent());
    }
    Response networkResponse = chain.proceed(requestBuilder.build());
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    Response.Builder responseBuilder = networkResponse.newBuilder().request(userRequest);
    if (transparentGzip && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding")) && HttpHeaders.hasBody(networkResponse)) {
        GzipSource responseBody = new GzipSource(networkResponse.body().source());
        Headers strippedHeaders = networkResponse.headers().newBuilder().removeAll("Content-Encoding").removeAll("Content-Length").build();
        responseBuilder.headers(strippedHeaders);
        responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
    }
    return responseBuilder.build();
}
Also used : Cookie(okhttp3.Cookie) Headers(okhttp3.Headers) Request(okhttp3.Request) Response(okhttp3.Response) GzipSource(okio.GzipSource) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 28 with Response

use of retrofit2.Response in project okhttp by square.

the class PublicSuffixListGenerator method main.

public static void main(String... args) throws IOException {
    OkHttpClient client = new OkHttpClient.Builder().build();
    Request request = new Request.Builder().url("https://publicsuffix.org/list/public_suffix_list.dat").build();
    SortedSet<ByteString> sortedRules = new TreeSet<>();
    SortedSet<ByteString> sortedExceptionRules = new TreeSet<>();
    try (Response response = client.newCall(request).execute()) {
        BufferedSource source = response.body().source();
        int totalRuleBytes = 0;
        int totalExceptionRuleBytes = 0;
        while (!source.exhausted()) {
            String line = source.readUtf8LineStrict();
            if (line.trim().isEmpty() || line.startsWith("//"))
                continue;
            if (line.contains(WILDCARD_CHAR)) {
                assertWildcardRule(line);
            }
            ByteString rule = ByteString.encodeUtf8(line);
            if (rule.startsWith(EXCEPTION_RULE_MARKER)) {
                rule = rule.substring(1);
                // We use '\n' for end of value.
                totalExceptionRuleBytes += rule.size() + 1;
                sortedExceptionRules.add(rule);
            } else {
                // We use '\n' for end of value.
                totalRuleBytes += rule.size() + 1;
                sortedRules.add(rule);
            }
        }
        File resources = new File(OKHTTP_RESOURCE_DIR);
        if (!resources.mkdirs() && !resources.exists()) {
            throw new RuntimeException("Unable to create resource directory!");
        }
        Sink fileSink = Okio.sink(new File(resources, PublicSuffixDatabase.PUBLIC_SUFFIX_RESOURCE));
        try (BufferedSink sink = Okio.buffer(new GzipSink(fileSink))) {
            sink.writeInt(totalRuleBytes);
            for (ByteString domain : sortedRules) {
                sink.write(domain).writeByte('\n');
            }
            sink.writeInt(totalExceptionRuleBytes);
            for (ByteString domain : sortedExceptionRules) {
                sink.write(domain).writeByte('\n');
            }
        }
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ByteString(okio.ByteString) GzipSink(okio.GzipSink) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) ByteString(okio.ByteString) Response(okhttp3.Response) Sink(okio.Sink) GzipSink(okio.GzipSink) BufferedSink(okio.BufferedSink) TreeSet(java.util.TreeSet) File(java.io.File) BufferedSource(okio.BufferedSource)

Example 29 with Response

use of retrofit2.Response in project okhttp by square.

the class PostExample method post.

String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).post(body).build();
    try (Response response = client.newCall(request).execute()) {
        return response.body().string();
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Example 30 with Response

use of retrofit2.Response in project okhttp by square.

the class AccessHeaders method run.

public void run() throws Exception {
    Request request = new Request.Builder().url("https://api.github.com/repos/square/okhttp/issues").header("User-Agent", "OkHttp Headers.java").addHeader("Accept", "application/json; q=0.5").addHeader("Accept", "application/vnd.github.v3+json").build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);
        System.out.println("Server: " + response.header("Server"));
        System.out.println("Date: " + response.header("Date"));
        System.out.println("Vary: " + response.headers("Vary"));
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException)

Aggregations

Response (okhttp3.Response)474 Request (okhttp3.Request)352 Test (org.junit.Test)237 IOException (java.io.IOException)188 Response (retrofit2.Response)156 ResponseBody (okhttp3.ResponseBody)148 ServiceResponse (com.microsoft.rest.ServiceResponse)114 Call (okhttp3.Call)102 MockResponse (okhttp3.mockwebserver.MockResponse)99 Observable (rx.Observable)98 OkHttpClient (okhttp3.OkHttpClient)72 RequestBody (okhttp3.RequestBody)71 Callback (okhttp3.Callback)43 List (java.util.List)40 TestClients.clientRequest (keywhiz.TestClients.clientRequest)37 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)34 Interceptor (okhttp3.Interceptor)29 HttpUrl (okhttp3.HttpUrl)27 MediaType (okhttp3.MediaType)26 Buffer (okio.Buffer)25