Example usage for com.squareup.okhttp MediaType parse

List of usage examples for com.squareup.okhttp MediaType parse

Introduction

In this page you can find the example usage for com.squareup.okhttp MediaType parse.

Prototype

public static MediaType parse(String string) 

Source Link

Document

Returns a media type for string , or null if string is not a well-formed media type.

Usage

From source file:com.tinspx.util.net.okhttp.OkHttpContext.java

License:Open Source License

static @Nullable RequestBody createRequestBody(Request request) throws IOException {
    if (!request.hasBody()) {
        return null;
    }/*from ww w .j a  v a2s  .c  o  m*/
    final com.tinspx.util.net.RequestBody body = request.body().get();
    String contentType = null;
    long len = -1;
    for (Map.Entry<String, String> header : body.headers().entries()) {
        String normalized = notNullTrimLower.apply(header.getKey());
        if (CONTENT_TYPE.equals(normalized)) {
            contentType = header.getValue().trim();
        } else if (CONTENT_LENGTH.equals(normalized)) {
            //invalid length will throw NumberFormatException
            //TODO: ignore this header and just use the body.size()?
            //maybe only use the header if hasKnownSize is false
            len = Long.parseLong(header.getValue().trim());
            checkState(len >= 0, "%s has an invalid Content-Length (%s)", body, len);
        } else {
            request.addHeader(header.getKey(), header.getValue());
        }
    }
    //content-type is not required
    final MediaType mediaType;
    if (contentType != null) {
        mediaType = MediaType.parse(contentType);
        checkState(mediaType != null, "%s has an invalid Content-Type (%s)", body, contentType);
    } else {
        mediaType = null;
    }
    final long contentLength = len;

    return new RequestBody() {
        final Object lock = new Object();
        /**
         * saving the exception is a hack that should work until okhttp
         * fixes RequestBody.
         */
        @GuardedBy("lock")
        IOException last;

        @Override
        public long contentLength() {
            if (contentLength >= 0) {
                return contentLength;
            }
            try {
                if (body.hasKnownSize()) {
                    return body.size();
                }
            } catch (IOException ex) {
                log.error("polling size of {}", body, ex);
                synchronized (lock) {
                    last = ex;
                }
            }
            return -1;
        }

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

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            synchronized (lock) {
                if (last != null) {
                    IOException ex = last;
                    last = null;
                    throw ex;
                }
            }
            body.copyTo(sink.outputStream());
        }
    };
}

From source file:com.vavian.mockretrofitrequests.rest.service.FakeInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Response response = null;/* w ww .jav a 2 s  .c  om*/
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "---- DEBUG --- DEBUG -- DEBUG - DEBUG -- DEBUG --- DEBUG ----");
        Log.d(TAG, "----                FAKE SERVER RESPONSES                ----");
        String responseString;
        // Get Request URI.
        final URI uri = chain.request().uri();
        Log.d(TAG, "---- Request URL: " + uri.toString());
        // Get Query String.
        final String query = uri.getQuery();
        // Parse the Query String.
        final String[] parsedQuery = query.split("=");
        if (parsedQuery[0].equalsIgnoreCase("id") && parsedQuery[1].equalsIgnoreCase("1")) {
            responseString = TEACHER_ID_1;
        } else if (parsedQuery[0].equalsIgnoreCase("id") && parsedQuery[1].equalsIgnoreCase("2")) {
            responseString = TEACHER_ID_2;
        } else {
            responseString = "";
        }

        response = new Response.Builder().code(200).message(responseString).request(chain.request())
                .protocol(Protocol.HTTP_1_0)
                .body(ResponseBody.create(MediaType.parse("application/json"), responseString.getBytes()))
                .addHeader("content-type", "application/json").build();

        Log.d(TAG, "---- DEBUG --- DEBUG -- DEBUG - DEBUG -- DEBUG --- DEBUG ----");
    } else {
        response = chain.proceed(chain.request());
    }

    return response;
}

From source file:com.wialon.remote.OkSdkHttpClient.java

License:Apache License

@Override
public void postFile(String url, Map<String, String> params, Callback callback, int timeout, File file) {
    //Method will work at 2.1 version of library https://github.com/square/okhttp/issues/963 and https://github.com/square/okhttp/pull/969
    MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    RequestBody paramsBody = paramsMapToRequestBody(params);
    if (paramsBody != null) {
        builder.addPart(paramsBody);/*from  w  w w. j  a  v  a  2 s . co  m*/
    }
    builder.addPart(RequestBody.create(MediaType.parse(""), file));
    Request request = new Request.Builder().url(url).post(builder.build()).build();
    threadPool.submit(new HttpRequest(getHttpClient(timeout), request, callback));
}

From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java

License:Open Source License

@Override
public void uploadTestRun(String testSpecificationId, FilePath workspace, String includes, String excludes,
        Map<String, Object> metadata, PrintStream logger) throws IOException, InterruptedException {
    if (testSpecificationId == null || testSpecificationId.isEmpty()) {
        throw new IllegalArgumentException(
                "No test specification id specified. Does the test specification still exist in XL TestView?");
    }/*from   ww w. ja v a2  s .c o  m*/
    try {
        logInfo(logger,
                format("Collecting files from '%s' using include pattern: '%s' and exclude pattern '%s'",
                        workspace.getRemote(), includes, excludes));

        DirScanner scanner = new DirScanner.Glob(includes, excludes);

        ObjectMapper objectMapper = new ObjectMapper();

        RequestBody body = new MultipartBuilder().type(MultipartBuilder.MIXED)
                .addPart(RequestBody.create(MediaType.parse(APPLICATION_JSON_UTF_8),
                        objectMapper.writeValueAsString(metadata)))
                .addPart(new ZipRequestBody(workspace, scanner, logger)).build();

        Request request = new Request.Builder()
                .url(createSensibleURL(API_IMPORT + "/" + testSpecificationId, serverUrl))
                .header("User-Agent", getUserAgent()).header("Accept", APPLICATION_JSON_UTF_8)
                .header("Authorization", createCredentials()).header("Transfer-Encoding", "chunked").post(body)
                .build();

        Response response = client.newCall(request).execute();
        ObjectMapper mapper = createMapper();
        ImportError importError;
        switch (response.code()) {
        case 200:
            logInfo(logger, "Sent data successfully");
            return;
        case 304:
            logWarn(logger, "No new results were detected. Nothing was imported.");
            throw new IllegalStateException("No new results were detected. Nothing was imported.");
        case 400:
            importError = mapper.readValue(response.body().byteStream(), ImportError.class);
            throw new IllegalStateException(importError.getMessage());
        case 401:
            throw new AuthenticationException(String.format(
                    "User '%s' and the supplied password are unable to log in", credentials.getUsername()));
        case 402:
            throw new PaymentRequiredException("The XL TestView server does not have a valid license");
        case 404:
            throw new ConnectionException("Cannot find test specification '" + testSpecificationId
                    + ". Please check if the XL TestView server is "
                    + "running and the test specification exists.");
        case 422:
            logWarn(logger, "Unable to process results.");
            logWarn(logger,
                    "Are you sure your include/exclude pattern provides all needed files for the test tool?");
            importError = mapper.readValue(response.body().byteStream(), ImportError.class);
            throw new IllegalStateException(importError.getMessage());
        default:
            throw new IllegalStateException("Unknown error. Status code: " + response.code()
                    + ". Response message: " + response.toString());
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        e.printStackTrace();
        LOG.warn("I/O error uploading test run data to {} {}\n{}", serverUrl.toString(), e.toString(), e);
        throw new IOException(
                "I/O error uploading test run data to " + serverUrl.toString() + " " + e.toString(), e);
    }
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAttachesFormFields() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", true).responseAs(Object.class).formField("f",
            "true");
    // Build the CallSpec so that we don't test this behaviour twice.
    builder.build().formField("e", "false");

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();//from w  w  w.j  a v a2s  .  c  o  m
    assertThat(body.contentType()).isEqualTo(MediaType.parse("application/x-www-form-urlencoded"));

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("f=true&e=false");
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAttachesFormFieldsAsLists() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", true).responseAs(Object.class).formField("f",
            "test1", "test2");
    // Build the CallSpec so that we don't test this behaviour twice.
    List<String> field = new ArrayList<>(2);
    field.add("test3");
    field.add("test4");
    builder.build().formField("e", field).formField("d", "test5", "test6");

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();/*from  www. ja  v a  2 s. c o  m*/
    assertThat(body.contentType()).isEqualTo(MediaType.parse("application/x-www-form-urlencoded"));

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("f=test1%2C%20test2&e=test3%2C%20test4&d=test5%2C%20test6");
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAllowsRawBody() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", false).responseAs(Object.class)
            .body(RequestBody.create(MediaType.parse("application/text"), "Hey!"));
    // Build the CallSpec so that we can build the request.
    builder.build();/*from w w  w .  j a v a2s . c  om*/

    Request request = builder.request();
    RequestBody body = request.body();
    assertThat(body.contentLength()).isEqualTo(4);
    assertThat(body.contentType().subtype()).isEqualTo("text");

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("Hey!");
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void exceptionCatchingBodyThrows() throws Exception {
    ResponseBody throwingBody = new ResponseBody() {
        @Override/*from ww  w .jav  a 2 s.  c o m*/
        public MediaType contentType() {
            //noinspection ConstantConditions
            return MediaType.parse("application/h");
        }

        @Override
        public long contentLength() throws IOException {
            throw new IOException("Broken body!");
        }

        @Override
        public BufferedSource source() throws IOException {
            throw new IOException("Broken body!");
        }
    };

    // Test content length throws
    ExceptionCatchingRequestBody body = new ExceptionCatchingRequestBody(throwingBody);
    assertThat(body.contentType()).isEqualTo(throwingBody.contentType());
    try {
        body.contentLength();
    } catch (IOException ignored) {
    }
    try {
        body.throwIfCaught();
    } catch (IOException e) {
        assertThat(e.getMessage()).isEqualTo("Broken body!");
    }

    // Test source throws, here we need new object
    body = new ExceptionCatchingRequestBody(throwingBody);
    assertThat(body.contentType()).isEqualTo(throwingBody.contentType());
    try {
        body.source();
    } catch (IOException ignored) {
    }
    try {
        body.throwIfCaught();
    } catch (IOException e) {
        assertThat(e.getMessage()).isEqualTo("Broken body!");
    }
}

From source file:com.xing.api.resources.ProfileEditingResourceTest.java

License:Apache License

@Test
public void updateOwnProfilePicture() throws Exception {
    // This is not a valid body, but the server prevents that in the real world.
    PictureUpload upload = PictureUpload.pictureUploadJPEG("picture.jpeg", new byte[0]);
    testVoidSpec(resource.updateProfilePicture(upload));

    RecordedRequest request = server.takeRequest(500, TimeUnit.MILLISECONDS);
    Buffer body = request.getBody();
    assertThat(body.readUtf8()).isEqualTo("{\"photo\":{" + "\"content\":[]," + "\"file_name\":\"picture.jpeg\","
            + "\"mime_type\":\"image/jpeg\"" + "}}");

    testVoidSpec(resource.updateProfilePicture(RequestBody.create(MediaType.parse("multipart/form-data"), "")));
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

void uploadFile(final String url, final File file, final long startOffset,
        final ProgressListener progressListener) throws IOException, HttpCodeException {
    logger.debug("uploadFile: put to url: " + url);
    MediaType mediaType = MediaType.parse("application/octet-stream");
    RequestBody requestBody = RequestBodyProgress.create(mediaType, file, startOffset, progressListener);
    Request.Builder requestBuilder = buildRequest().removeHeader(Credentials.AUTHORIZATION_HEADER).url(url)
            .put(requestBody);//from w w w.  j  a  v a2 s .c  o m
    if (startOffset > 0) {
        StringBuilder contentRange = new StringBuilder();
        contentRange.append("bytes ").append(startOffset).append("-").append(file.length() - 1).append("/")
                .append(file.length());
        logger.debug(CONTENT_RANGE_HEADER + ": " + contentRange);
        requestBuilder.addHeader(CONTENT_RANGE_HEADER, contentRange.toString());
    }
    Request request = requestBuilder.build();

    Response response = client.newCall(request).execute();

    String statusLine = response.message();
    logger.debug("headUrl: " + statusLine + " for url " + url);

    int code = response.code();

    ResponseBody responseBody = response.body();
    responseBody.close();

    switch (code) {
    case 201:
    case 202:
        logger.debug("uploadFile: file uploaded successfully: " + file);
        break;
    case 404:
        throw new NotFoundException(code, null);
    case 409:
        throw new ConflictException(code, null);
    case 412:
        throw new PreconditionFailedException(code, null);
    case 413:
        throw new FileTooBigException(code, null);
    case 503:
        throw new ServiceUnavailableException(code, null);
    case 507:
        throw new InsufficientStorageException(code, null);
    default:
        throw new HttpCodeException(code);
    }
}