Search in sources :

Example 56 with MediaType

use of okhttp3.MediaType in project serverless by bluenimble.

the class HttpRemote method request.

private boolean request(ApiVerb verb, JsonObject spec, Callback callback, ApiStreamSource... attachments) {
    JsonObject rdata = Json.getObject(spec, Spec.Data);
    if (!Json.isNullOrEmpty(featureSpec)) {
        JsonObject master = featureSpec.duplicate();
        Json.resolve(master, ECompiler, new VariableResolver() {

            private static final long serialVersionUID = 1L;

            @Override
            public Object resolve(String namespace, String... property) {
                Object v = Json.find(rdata, property);
                Json.remove(rdata, property);
                return v;
            }
        });
        spec = master.merge(spec);
    }
    String endpoint = Json.getString(spec, Spec.Endpoint);
    String path = Json.getString(spec, Spec.Path);
    if (!Lang.isNullOrEmpty(path)) {
        endpoint += path;
    }
    Serializer.Name serName = null;
    try {
        serName = Serializer.Name.valueOf(Json.getString(spec, Spec.Serializer, Serializer.Name.text.name()).toLowerCase());
    } catch (Exception ex) {
        // ignore
        serName = Serializer.Name.text;
    }
    Serializer serializer = Serializers.get(serName);
    Request request = null;
    Response response = null;
    try {
        // contentType
        String contentType = null;
        // resole and add headers
        JsonObject headers = Json.getObject(spec, Spec.Headers);
        if (!Json.isNullOrEmpty(headers)) {
            Json.resolve(headers, ECompiler, new VariableResolver() {

                private static final long serialVersionUID = 1L;

                @Override
                public Object resolve(String namespace, String... property) {
                    return Json.find(rdata, property);
                }
            });
            Iterator<String> hnames = headers.keys();
            while (hnames.hasNext()) {
                String hn = hnames.next();
                String hv = Json.getString(headers, hn);
                if (HttpHeaders.CONTENT_TYPE.toUpperCase().equals(hn.toUpperCase())) {
                    contentType = hv;
                }
            }
        }
        if (Lang.isNullOrEmpty(contentType)) {
            contentType = ContentTypes.FormUrlEncoded;
        }
        contentType = contentType.trim();
        MediaType mediaType = MediaTypes.get(contentType);
        RequestBody body = null;
        List<RequestParameter> parameters = null;
        if (attachments != null && attachments.length > 0 && !Json.isNullOrEmpty(rdata)) {
            // multipart body
            MultipartBody.Builder builder = new MultipartBody.Builder();
            Iterator<String> pnames = rdata.keys();
            while (pnames.hasNext()) {
                String pn = pnames.next();
                builder.addFormDataPart(pn, String.valueOf(rdata.get(pn)));
            }
            for (ApiStreamSource ss : attachments) {
                try {
                    builder.addFormDataPart(ss.name(), ss.name(), RequestBody.create(MediaType.parse(contentType), IOUtils.toByteArray(ss.stream())));
                } catch (Exception ex) {
                    callback.onError(Error.Other, ex.getMessage());
                    return false;
                }
            }
        } else if (contentType.startsWith(ContentTypes.Json)) {
            body = RequestBody.create(mediaType, rdata == null ? JsonObject.EMPTY_OBJECT : rdata.toString());
        } else {
            if (!Json.isNullOrEmpty(rdata)) {
                // for bnb signature only
                if (Signers.Bnb.equals(Json.find(spec, Spec.Sign, Spec.SignProtocol))) {
                    parameters = new ArrayList<RequestParameter>();
                }
                if (verb.equals(ApiVerb.POST) || verb.equals(ApiVerb.PUT) || verb.equals(ApiVerb.PATCH)) {
                    FormBody.Builder fb = new FormBody.Builder();
                    Iterator<String> pnames = rdata.keys();
                    while (pnames.hasNext()) {
                        String pn = pnames.next();
                        fb.add(pn, String.valueOf(rdata.get(pn)));
                        if (parameters != null) {
                            parameters.add(new RequestParameter(pn, rdata.get(pn)));
                        }
                    }
                    body = fb.build();
                } else if (verb.equals(ApiVerb.GET)) {
                    HttpUrl.Builder urlBuilder = HttpUrl.parse(endpoint).newBuilder();
                    Iterator<String> pnames = rdata.keys();
                    while (pnames.hasNext()) {
                        String pn = pnames.next();
                        urlBuilder.addQueryParameter(pn, String.valueOf(rdata.get(pn)));
                        if (parameters != null) {
                            parameters.add(new RequestParameter(pn, rdata.get(pn)));
                        }
                    }
                    endpoint = urlBuilder.build().toString();
                }
            }
        }
        // create the request builder
        Request.Builder rBuilder = new Request.Builder().url(endpoint);
        rBuilder.header(HttpHeaders.USER_AGENT, DefaultUserAgent);
        // add headers
        if (!Json.isNullOrEmpty(headers)) {
            Iterator<String> hnames = headers.keys();
            while (hnames.hasNext()) {
                String hn = hnames.next();
                String hv = Json.getString(headers, hn);
                rBuilder.header(hn, hv);
            }
        }
        // create request
        switch(verb) {
            case GET:
                rBuilder.get();
                break;
            case POST:
                rBuilder.post(body);
                break;
            case DELETE:
                rBuilder.delete();
                break;
            case PUT:
                rBuilder.put(body);
                break;
            case PATCH:
                rBuilder.patch(body);
                break;
            case HEAD:
                rBuilder.head();
                break;
            default:
                break;
        }
        // build then sign
        request = sign(rBuilder.build(), spec, parameters);
        response = http.newCall(request).execute();
        if (response.code() > Json.getInteger(spec, Spec.SuccessCode, 202)) {
            callback.onError(response.code(), response.body().string());
            return false;
        } else {
            callback.onSuccess(response.code(), serializer.serialize(response.body().byteStream()));
            return true;
        }
    } catch (UnknownHostException uhex) {
        callback.onError(Error.UnknownHost, "Endpoint " + endpoint + " can't be resolved. Check your internet connection and make sure the endpoint is correct");
        return false;
    } catch (SocketTimeoutException stoex) {
        callback.onError(Error.Timeout, "Endpoint " + endpoint + " was found but " + stoex.getMessage());
        return false;
    } catch (Exception ex) {
        callback.onError(Error.Other, Lang.toError(ex));
        return false;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(com.bluenimble.platform.json.JsonObject) Iterator(java.util.Iterator) MediaType(okhttp3.MediaType) TextSerializer(com.bluenimble.platform.remote.impls.serializers.TextSerializer) Serializer(com.bluenimble.platform.remote.Serializer) StreamSerializer(com.bluenimble.platform.remote.impls.serializers.StreamSerializer) JsonSerializer(com.bluenimble.platform.remote.impls.serializers.JsonSerializer) XmlSerializer(com.bluenimble.platform.remote.impls.serializers.XmlSerializer) RequestBody(okhttp3.RequestBody) UnknownHostException(java.net.UnknownHostException) Request(okhttp3.Request) FormBody(okhttp3.FormBody) ApiStreamSource(com.bluenimble.platform.api.ApiStreamSource) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) SocketTimeoutException(java.net.SocketTimeoutException) MultipartBody(okhttp3.MultipartBody) JsonObject(com.bluenimble.platform.json.JsonObject) VariableResolver(com.bluenimble.platform.templating.VariableResolver)

Example 57 with MediaType

use of okhttp3.MediaType in project okhttp by square.

the class HttpLoggingInterceptorTest method duplexRequestsAreNotLogged.

@Test
public void duplexRequestsAreNotLogged() throws Exception {
    platform.assumeHttp2Support();
    platform.assumeNotBouncyCastle();
    // HTTP/2
    server.useHttps(handshakeCertificates.sslSocketFactory(), false);
    url = server.url("/");
    setLevel(Level.BODY);
    server.enqueue(new MockResponse().setBody("Hello response!"));
    RequestBody asyncRequestBody = new RequestBody() {

        @Override
        @Nullable
        public MediaType contentType() {
            return null;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Hello request!");
            sink.close();
        }

        @Override
        public boolean isDuplex() {
            return true;
        }
    };
    Request request = request().post(asyncRequestBody).build();
    Response response = client.newCall(request).execute();
    assumeTrue(response.protocol().equals(Protocol.HTTP_2));
    assertThat(response.body().string()).isEqualTo("Hello response!");
    applicationLogs.assertLogEqual("--> POST " + url).assertLogEqual("--> END POST (duplex request body omitted)").assertLogMatch("<-- 200 " + url + " \\(\\d+ms\\)").assertLogEqual("content-length: 15").assertLogEqual("").assertLogEqual("Hello response!").assertLogEqual("<-- END HTTP (15-byte body)").assertNoMoreLogs();
}
Also used : Response(okhttp3.Response) MockResponse(mockwebserver3.MockResponse) MockResponse(mockwebserver3.MockResponse) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) RequestBody(okhttp3.RequestBody) Test(org.junit.jupiter.api.Test)

Example 58 with MediaType

use of okhttp3.MediaType in project okhttp by square.

the class PostStreaming method run.

public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {

        @Override
        public MediaType contentType() {
            return MEDIA_TYPE_MARKDOWN;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Numbers\n");
            sink.writeUtf8("-------\n");
            for (int i = 2; i <= 997; i++) {
                sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
            }
        }

        private String factor(int n) {
            for (int i = 2; i < n; i++) {
                int x = n / i;
                if (x * i == n)
                    return factor(x) + " × " + i;
            }
            return Integer.toString(n);
        }
    };
    Request request = new Request.Builder().url("https://api.github.com/markdown/raw").post(requestBody).build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);
        System.out.println(response.body().string());
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 59 with MediaType

use of okhttp3.MediaType in project okhttp by square.

the class InterceptorTest method networkInterceptorsCanChangeRequestMethodFromGetToPost.

@Test
public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception {
    server.enqueue(new MockResponse());
    Interceptor interceptor = chain -> {
        Request originalRequest = chain.request();
        MediaType mediaType = MediaType.get("text/plain");
        RequestBody body = RequestBody.create("abc", mediaType);
        return chain.proceed(originalRequest.newBuilder().method("POST", body).header("Content-Type", mediaType.toString()).header("Content-Length", Long.toString(body.contentLength())).build());
    };
    client = client.newBuilder().addNetworkInterceptor(interceptor).build();
    Request request = new Request.Builder().url(server.url("/")).get().build();
    client.newCall(request).execute();
    RecordedRequest recordedRequest = server.takeRequest();
    assertThat(recordedRequest.getMethod()).isEqualTo("POST");
    assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("abc");
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Okio(okio.Okio) BeforeEach(org.junit.jupiter.api.BeforeEach) Socket(java.net.Socket) Source(okio.Source) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicReference(java.util.concurrent.atomic.AtomicReference) Sink(okio.Sink) MockWebServer(mockwebserver3.MockWebServer) InetAddress(java.net.InetAddress) ServerSocket(java.net.ServerSocket) SocketPolicy(mockwebserver3.SocketPolicy) BufferedSink(okio.BufferedSink) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Locale(java.util.Locale) SocketTimeoutException(java.net.SocketTimeoutException) Duration(java.time.Duration) ForwardingSource(okio.ForwardingSource) Tag(org.junit.jupiter.api.Tag) Buffer(okio.Buffer) SynchronousQueue(java.util.concurrent.SynchronousQueue) IOException(java.io.IOException) BlockingQueue(java.util.concurrent.BlockingQueue) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Unit(kotlin.Unit) GzipSink(okio.GzipSink) ForwardingSink(okio.ForwardingSink) MockResponse(mockwebserver3.MockResponse) TestUtil.assertSuppressed(okhttp3.TestUtil.assertSuppressed) RecordedRequest(mockwebserver3.RecordedRequest) RecordedRequest(mockwebserver3.RecordedRequest) MockResponse(mockwebserver3.MockResponse) RecordedRequest(mockwebserver3.RecordedRequest) Test(org.junit.jupiter.api.Test)

Example 60 with MediaType

use of okhttp3.MediaType in project okhttp by square.

the class DuplexTest method serverCancelsRequestBodyAndSendsResponseBody.

/**
 * OkHttp currently doesn't implement failing the request body stream independently of failing the
 * corresponding response body stream. This is necessary if we want servers to be able to stop
 * inbound data and send an early 400 before the request body completes.
 *
 * This test sends a slow request that is canceled by the server. It expects the response to still
 * be readable after the request stream is canceled.
 */
@Disabled
@Test
public void serverCancelsRequestBodyAndSendsResponseBody() throws Exception {
    client = client.newBuilder().retryOnConnectionFailure(false).build();
    BlockingQueue<String> log = new LinkedBlockingQueue<>();
    enableProtocol(Protocol.HTTP_2);
    MockDuplexResponseBody mockDuplexResponseBody = enqueueResponseWithBody(new MockResponse().clearHeaders(), new MockDuplexResponseBody().sendResponse("success!").exhaustResponse().cancelStream(ErrorCode.NO_ERROR));
    Call call = client.newCall(new Request.Builder().url(server.url("/")).post(new RequestBody() {

        @Override
        @Nullable
        public MediaType contentType() {
            return null;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            try {
                for (int i = 0; i < 10; i++) {
                    sink.writeUtf8(".");
                    sink.flush();
                    Thread.sleep(100);
                }
            } catch (IOException e) {
                log.add(e.toString());
                throw e;
            } catch (Exception e) {
                log.add(e.toString());
            }
        }
    }).build());
    try (Response response = call.execute()) {
        assertThat(response.body().string()).isEqualTo("success!");
    }
    mockDuplexResponseBody.awaitSuccess();
    assertThat(log.take()).contains("StreamResetException: stream was reset: NO_ERROR");
}
Also used : MockResponse(mockwebserver3.MockResponse) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException) MockResponse(mockwebserver3.MockResponse) MockDuplexResponseBody(mockwebserver3.internal.duplex.MockDuplexResponseBody) Nullable(org.jetbrains.annotations.Nullable) AsyncRequestBody(okhttp3.internal.duplex.AsyncRequestBody) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Aggregations

MediaType (okhttp3.MediaType)103 RequestBody (okhttp3.RequestBody)95 Request (okhttp3.Request)86 Response (okhttp3.Response)78 IOException (java.io.IOException)73 ResponseBody (okhttp3.ResponseBody)36 BufferedSink (okio.BufferedSink)34 Buffer (okio.Buffer)30 Charset (java.nio.charset.Charset)26 Headers (okhttp3.Headers)19 BufferedSource (okio.BufferedSource)19 Map (java.util.Map)17 OkHttpClient (okhttp3.OkHttpClient)17 InputStream (java.io.InputStream)12 HashMap (java.util.HashMap)12 MultipartBody (okhttp3.MultipartBody)12 MockResponse (okhttp3.mockwebserver.MockResponse)11 EOFException (java.io.EOFException)10 GzipSink (okio.GzipSink)10 JSONObject (org.json.JSONObject)10