Search in sources :

Example 6 with MediaType

use of okhttp3.MediaType in project scribejava by scribejava.

the class OkHttpHttpClient method createCall.

private Call createCall(String userAgent, Map<String, String> headers, Verb httpVerb, String completeUrl, BodyType bodyType, Object bodyContents) {
    final Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(completeUrl);
    final String method = httpVerb.name();
    // prepare body
    final RequestBody body;
    if (bodyContents != null && HttpMethod.permitsRequestBody(method)) {
        final MediaType mediaType = headers.containsKey(CONTENT_TYPE) ? MediaType.parse(headers.get(CONTENT_TYPE)) : DEFAULT_CONTENT_TYPE_MEDIA_TYPE;
        body = bodyType.createBody(mediaType, bodyContents);
    } else {
        body = null;
    }
    // fill HTTP method and body
    requestBuilder.method(method, body);
    // fill headers
    for (Map.Entry<String, String> header : headers.entrySet()) {
        requestBuilder.addHeader(header.getKey(), header.getValue());
    }
    if (userAgent != null) {
        requestBuilder.header(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent);
    }
    // create a new call
    return client.newCall(requestBuilder.build());
}
Also used : Request(okhttp3.Request) OAuthRequest(com.github.scribejava.core.model.OAuthRequest) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 7 with MediaType

use of okhttp3.MediaType in project graphhopper by graphhopper.

the class BaseServletTester method post.

protected String post(String path, int expectedStatusCode, String xmlOrJson) throws IOException {
    String url = getTestAPIUrl(path);
    MediaType type;
    if (xmlOrJson.startsWith("<")) {
        type = MT_XML;
    } else {
        type = MT_JSON;
    }
    Response rsp = client.newCall(new Request.Builder().url(url).post(RequestBody.create(type, xmlOrJson)).build()).execute();
    assertEquals(url + ", http status was:" + rsp.code(), HttpStatus.getMessage(expectedStatusCode), HttpStatus.getMessage(rsp.code()));
    return rsp.body().string();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) MediaType(okhttp3.MediaType)

Example 8 with MediaType

use of okhttp3.MediaType in project okhttp by square.

the class CallTest method reusedSinksGetIndependentTimeoutInstances.

@Test
public void reusedSinksGetIndependentTimeoutInstances() throws Exception {
    server.enqueue(new MockResponse());
    server.enqueue(new MockResponse());
    // Call 1: set a deadline on the request body.
    RequestBody requestBody1 = new RequestBody() {

        @Override
        public MediaType contentType() {
            return MediaType.parse("text/plain");
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("abc");
            sink.timeout().deadline(5, TimeUnit.SECONDS);
        }
    };
    Request request1 = new Request.Builder().url(server.url("/")).method("POST", requestBody1).build();
    Response response1 = client.newCall(request1).execute();
    assertEquals(200, response1.code());
    // Call 2: check for the absence of a deadline on the request body.
    RequestBody requestBody2 = new RequestBody() {

        @Override
        public MediaType contentType() {
            return MediaType.parse("text/plain");
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            assertFalse(sink.timeout().hasDeadline());
            sink.writeUtf8("def");
        }
    };
    Request request2 = new Request.Builder().url(server.url("/")).method("POST", requestBody2).build();
    Response response2 = client.newCall(request2).execute();
    assertEquals(200, response2.code());
    // Use sequence numbers to confirm the connection was pooled.
    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(1, server.takeRequest().getSequenceNumber());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) BufferedSink(okio.BufferedSink) Test(org.junit.Test)

Example 9 with MediaType

use of okhttp3.MediaType 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 10 with MediaType

use of okhttp3.MediaType in project okhttp by square.

the class JavaApiConverterTest method createResponseBody.

private static ResponseBody createResponseBody(String bodyText) {
    final Buffer source = new Buffer().writeUtf8(bodyText);
    final long contentLength = source.size();
    return new ResponseBody() {

        @Override
        public MediaType contentType() {
            return MediaType.parse("text/plain; charset=utf-8");
        }

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

        @Override
        public BufferedSource source() {
            return source;
        }
    };
}
Also used : Buffer(okio.Buffer) ResponseBody(okhttp3.ResponseBody)

Aggregations

MediaType (okhttp3.MediaType)99 RequestBody (okhttp3.RequestBody)86 Request (okhttp3.Request)82 Response (okhttp3.Response)74 IOException (java.io.IOException)67 ResponseBody (okhttp3.ResponseBody)35 Buffer (okio.Buffer)30 BufferedSink (okio.BufferedSink)28 Charset (java.nio.charset.Charset)25 Headers (okhttp3.Headers)19 BufferedSource (okio.BufferedSource)19 Map (java.util.Map)17 OkHttpClient (okhttp3.OkHttpClient)15 HashMap (java.util.HashMap)12 InputStream (java.io.InputStream)11 MultipartBody (okhttp3.MultipartBody)11 MockResponse (okhttp3.mockwebserver.MockResponse)11 EOFException (java.io.EOFException)10 List (java.util.List)9 Connection (okhttp3.Connection)9