Search in sources :

Example 41 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class PostMultipart method run.

public void run() throws Exception {
    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("title", "Square Logo").addFormDataPart("image", "logo-square.png", RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))).build();
    Request request = new Request.Builder().header("Authorization", "Client-ID " + IMGUR_CLIENT_ID).url("https://api.imgur.com/3/image").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) IOException(java.io.IOException) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 42 with RequestBody

use of okhttp3.RequestBody 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 43 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class RequestBodyCompression method run.

public void run() throws Exception {
    Map<String, String> requestBody = new LinkedHashMap<>();
    requestBody.put("longUrl", "https://publicobject.com/2014/12/04/html-formatting-javadocs/");
    RequestBody jsonRequestBody = RequestBody.create(MEDIA_TYPE_JSON, mapJsonAdapter.toJson(requestBody));
    Request request = new Request.Builder().url("https://www.googleapis.com/urlshortener/v1/url?key=" + GOOGLE_API_KEY).post(jsonRequestBody).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) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) RequestBody(okhttp3.RequestBody)

Example 44 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class CallTest method upload.

private void upload(final boolean chunked, final int size, final int writeSize) throws Exception {
    server.enqueue(new MockResponse());
    executeSynchronously(new Request.Builder().url(server.url("/")).post(requestBody(chunked, size, writeSize)).build());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse)

Example 45 with RequestBody

use of okhttp3.RequestBody in project okhttp by square.

the class OkHttpURLConnection method buildCall.

private Call buildCall() throws IOException {
    if (call != null) {
        return call;
    }
    connected = true;
    if (doOutput) {
        if (method.equals("GET")) {
            // they are requesting a stream to write to. This implies a POST method
            method = "POST";
        } else if (!HttpMethod.permitsRequestBody(method)) {
            throw new ProtocolException(method + " does not support writing");
        }
    }
    if (requestHeaders.get("User-Agent") == null) {
        requestHeaders.add("User-Agent", defaultUserAgent());
    }
    OutputStreamRequestBody requestBody = null;
    if (HttpMethod.permitsRequestBody(method)) {
        // Add a content type for the request body, if one isn't already present.
        String contentType = requestHeaders.get("Content-Type");
        if (contentType == null) {
            contentType = "application/x-www-form-urlencoded";
            requestHeaders.add("Content-Type", contentType);
        }
        boolean stream = fixedContentLength != -1L || chunkLength > 0;
        long contentLength = -1L;
        String contentLengthString = requestHeaders.get("Content-Length");
        if (fixedContentLength != -1L) {
            contentLength = fixedContentLength;
        } else if (contentLengthString != null) {
            contentLength = Long.parseLong(contentLengthString);
        }
        requestBody = stream ? new StreamedRequestBody(contentLength) : new BufferedRequestBody(contentLength);
        requestBody.timeout().timeout(client.writeTimeoutMillis(), TimeUnit.MILLISECONDS);
    }
    Request request = new Request.Builder().url(Internal.instance.getHttpUrlChecked(getURL().toString())).headers(requestHeaders.build()).method(method, requestBody).build();
    if (urlFilter != null) {
        urlFilter.checkURLPermitted(request.url().url());
    }
    OkHttpClient.Builder clientBuilder = client.newBuilder();
    clientBuilder.interceptors().clear();
    clientBuilder.interceptors().add(UnexpectedException.INTERCEPTOR);
    clientBuilder.networkInterceptors().clear();
    clientBuilder.networkInterceptors().add(networkInterceptor);
    // Use a separate dispatcher so that limits aren't impacted. But use the same executor service!
    clientBuilder.dispatcher(new Dispatcher(client.dispatcher().executorService()));
    // If we're currently not using caches, make sure the engine's client doesn't have one.
    if (!getUseCaches()) {
        clientBuilder.cache(null);
    }
    return call = clientBuilder.build().newCall(request);
}
Also used : ProtocolException(java.net.ProtocolException) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Dispatcher(okhttp3.Dispatcher)

Aggregations

RequestBody (okhttp3.RequestBody)178 Request (okhttp3.Request)141 IOException (java.io.IOException)75 Response (okhttp3.Response)74 Test (org.junit.Test)53 ResponseBody (okhttp3.ResponseBody)32 Call (okhttp3.Call)31 MultipartBody (okhttp3.MultipartBody)28 MediaType (okhttp3.MediaType)27 FormBody (okhttp3.FormBody)25 Callback (okhttp3.Callback)23 Buffer (okio.Buffer)23 MockResponse (okhttp3.mockwebserver.MockResponse)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestClients.clientRequest (keywhiz.TestClients.clientRequest)15 BufferedSink (okio.BufferedSink)15 Headers (okhttp3.Headers)12 HttpUrl (okhttp3.HttpUrl)11 JSONObject (org.json.JSONObject)11 Body (retrofit2.http.Body)11