Example usage for com.squareup.okhttp ResponseBody string

List of usage examples for com.squareup.okhttp ResponseBody string

Introduction

In this page you can find the example usage for com.squareup.okhttp ResponseBody string.

Prototype

public final String string() throws IOException 

Source Link

Document

Returns the response as a string decoded with the charset of the Content-Type header.

Usage

From source file:com.cy.retrofithttpstest.retrofit.ToStringConverterFactory.java

License:Apache License

@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
    if (String.class.equals(type)) {
        return new Converter<ResponseBody, String>() {
            @Override// www  . j a va2 s. c  om
            public String convert(ResponseBody value) throws IOException {
                return value.string();
            }
        };
    }
    return null;
}

From source file:com.facebook.react.devsupport.DevServerHelper.java

License:Open Source License

public void isPackagerRunning(final PackagerStatusCallback callback) {
    String statusURL = createPacakgerStatusURL(getDebugServerHost());
    Request request = new Request.Builder().url(statusURL).build();

    mClient.newCall(request).enqueue(new Callback() {
        @Override//from   w w w . j  ava2  s . c  om
        public void onFailure(Request request, IOException e) {
            Log.e(ReactConstants.TAG, "IOException requesting status from packager", e);
            callback.onPackagerStatusFetched(false);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                Log.e(ReactConstants.TAG,
                        "Got non-success http code from packager when requesting status: " + response.code());
                callback.onPackagerStatusFetched(false);
                return;
            }
            ResponseBody body = response.body();
            if (body == null) {
                Log.e(ReactConstants.TAG, "Got null body response from packager when requesting status");
                callback.onPackagerStatusFetched(false);
                return;
            }
            if (!PACKAGER_OK_STATUS.equals(body.string())) {
                Log.e(ReactConstants.TAG,
                        "Got unexpected response from packager when requesting status: " + body.string());
                callback.onPackagerStatusFetched(false);
                return;
            }
            callback.onPackagerStatusFetched(true);
        }
    });
}

From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.GsonConverter.java

License:Apache License

public T fromBody(ResponseBody value, Request request) throws IOException {
    String string = value.string();
    System.out.println(":" + string);
    Reader reader = new InputStreamReader((new ByteArrayInputStream(string.getBytes(UTF8))), Util.UTF_8);
    try {//from  ww w  . ja  va  2 s  . c o  m
        T t = typeAdapter.fromJson(reader);
        System.out.println("?" + t);
        String mimeType = value.contentType().toString();
        parseCache(request, t, string, mimeType);
        return t;
    } finally {
        closeQuietly(reader);
    }
}

From source file:com.magnet.max.android.rest.marshalling.MagnetGsonConverter.java

License:Apache License

@Override
public T fromBody(ResponseBody responseBody) throws IOException {
    if (GsonDecorator.getInstance().isVoidType(typeToken.getType())) {
        return null;
    }// w  w  w . j a  v a  2 s .  c om

    if (typeToken.getRawType().equals(ResponseBody.class)) {
        return (T) responseBody;
    }

    if (GsonDecorator.getInstance().isByteArray(typeToken)) {
        return (T) responseBody.bytes();
    }

    //Charset charset = UTF_8;
    //if (responseBody.contentType() != null) {
    //  charset = responseBody.contentType().charset(charset);
    //}

    if (GsonDecorator.getInstance().isSimpleType(typeToken)) {
        return (T) GsonDecorator.getInstance().unmarshalSimpleType(responseBody.string(), typeToken.getType());
    } else {
        Reader in = responseBody.charStream();
        try {
            return (T) GsonDecorator.getInstance().fromJson(responseBody.charStream(), typeToken); //typeAdapter.fromJson(in);
        } catch (Exception e) {
            Log.e(TAG, "Error in fromBody \n" + e.getMessage());
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.malin.rengwuxianrxjava.activity.MainActivity.java

License:Open Source License

/**
 * Retrofit,?androidmalinGitHub?/* ww w .  j a v  a 2s  . c  o m*/
 */
private void method21() {

    mProgressBar.setVisibility(View.VISIBLE);
    mImageView.setVisibility(View.GONE);
    mResultTextView.setVisibility(View.VISIBLE);
    mResultTextView.setText("");
    Call call = RetrofitService.getInstance().createGitHubApi().getUser("androidmalin");

    //asynchronous
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Response response, Retrofit retrofit) {
            User user = (User) response.body();

            if (user == null) {
                //404 or the response cannot be converted to User.
                ResponseBody responseBody = response.errorBody();
                if (responseBody != null) {
                    try {
                        Logger.d("responseBody = " + responseBody.string());
                        mResultTextView.setText("responseBody = " + responseBody.string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Logger.d("responseBody = null");
                    mResultTextView.setText("responseBody = null");
                }
            } else {
                //200
                String message = "Github Name :" + user.name + "\nWebsite :" + user.blog + "\nCompany Name :"
                        + user.company;
                ToastUtil.getInstance().showToast(MainActivity.this, message);
                Logger.d(message);
                mResultTextView.setText(message);
            }
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onFailure(Throwable t) {
            Logger.d("t = " + t.getMessage());
            mProgressBar.setVisibility(View.GONE);
        }
    });
}

From source file:com.microsoft.azure.AzureClient.java

License:Open Source License

/**
 * Handles an initial response from a PUT or PATCH operation response by polling
 * the status of the operation until the long running operation terminates.
 *
 * @param response  the initial response from the PUT or PATCH operation.
 * @param <T>       the return type of the caller
 * @param resourceType the type of the resource
 * @return          the terminal response for the operation.
 * @throws CloudException REST exception
 * @throws InterruptedException interrupted exception
 * @throws IOException thrown by deserialization
 *//*  w w w  .ja v a  2s.  co m*/
public <T> ServiceResponse<T> getPutOrPatchResult(Response<ResponseBody> response, Type resourceType)
        throws CloudException, InterruptedException, IOException {
    if (response == null) {
        throw new CloudException("response is null.");
    }

    int statusCode = response.code();
    ResponseBody responseBody;
    if (response.isSuccess()) {
        responseBody = response.body();
    } else {
        responseBody = response.errorBody();
    }
    if (statusCode != 200 && statusCode != 201 && statusCode != 202) {
        CloudException exception = new CloudException(statusCode + " is not a valid polling status code");
        exception.setResponse(response);
        if (responseBody != null) {
            exception.setBody((CloudError) mapperAdapter.deserialize(responseBody.string(), CloudError.class));
        }
        throw exception;
    }

    PollingState<T> pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(),
            resourceType);
    String url = response.raw().request().urlString();

    // Check provisioning state
    while (!AzureAsyncOperation.getTerminalStatuses().contains(pollingState.getStatus())) {
        Thread.sleep(pollingState.getDelayInMilliseconds());

        if (pollingState.getAzureAsyncOperationHeaderLink() != null
                && !pollingState.getAzureAsyncOperationHeaderLink().isEmpty()) {
            updateStateFromAzureAsyncOperationHeader(pollingState);
        } else if (pollingState.getLocationHeaderLink() != null
                && !pollingState.getLocationHeaderLink().isEmpty()) {
            updateStateFromLocationHeaderOnPut(pollingState);
        } else {
            updateStateFromGetResourceOperation(pollingState, url);
        }
    }

    if (AzureAsyncOperation.SUCCESS_STATUS.equals(pollingState.getStatus())
            && pollingState.getResource() == null) {
        updateStateFromGetResourceOperation(pollingState, url);
    }

    if (AzureAsyncOperation.getFailedStatuses().contains(pollingState.getStatus())) {
        throw new CloudException("Async operation failed");
    }

    return new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse());
}

From source file:com.microsoft.azure.AzureClient.java

License:Open Source License

/**
 * Handles an initial response from a PUT or PATCH operation response by polling
 * the status of the operation asynchronously, calling the user provided callback
 * when the operation terminates.//from w w  w  .j  a  va  2s  .co m
 *
 * @param response  the initial response from the PUT or PATCH operation.
 * @param <T>       the return type of the caller.
 * @param resourceType the type of the resource.
 * @param callback  the user callback to call when operation terminates.
 * @return          the task describing the asynchronous polling.
 */
public <T> AsyncPollingTask<T> getPutOrPatchResultAsync(Response<ResponseBody> response, Type resourceType,
        ServiceCallback<T> callback) {
    if (response == null) {
        callback.failure(new ServiceException("response is null."));
        return null;
    }

    int statusCode = response.code();
    ResponseBody responseBody;
    if (response.isSuccess()) {
        responseBody = response.body();
    } else {
        responseBody = response.errorBody();
    }
    if (statusCode != 200 && statusCode != 201 && statusCode != 202) {
        CloudException exception = new CloudException(statusCode + " is not a valid polling status code");
        exception.setResponse(response);
        try {
            if (responseBody != null) {
                exception.setBody(
                        (CloudError) mapperAdapter.deserialize(responseBody.string(), CloudError.class));
            }
        } catch (Exception e) {
            /* ignore serialization errors on top of service errors */ }
        callback.failure(exception);
        return null;
    }

    PollingState<T> pollingState;
    try {
        pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType);
    } catch (IOException e) {
        callback.failure(e);
        return null;
    }
    String url = response.raw().request().urlString();

    // Task runner will take it from here
    PutPatchPollingTask<T> task = new PutPatchPollingTask<>(pollingState, url, callback);
    executor.schedule(task, pollingState.getDelayInMilliseconds(), TimeUnit.MILLISECONDS);
    return task;
}

From source file:com.microsoft.azure.AzureClient.java

License:Open Source License

/**
 * Handles an initial response from a POST or DELETE operation response by polling
 * the status of the operation until the long running operation terminates.
 *
 * @param response  the initial response from the POST or DELETE operation.
 * @param <T>       the return type of the caller
 * @param resourceType the type of the resource
 * @return          the terminal response for the operation.
 * @throws CloudException REST exception
 * @throws InterruptedException interrupted exception
 * @throws IOException thrown by deserialization
 */// w ww .  j a v a2 s.  c  o  m
public <T> ServiceResponse<T> getPostOrDeleteResult(Response<ResponseBody> response, Type resourceType)
        throws CloudException, InterruptedException, IOException {
    if (response == null) {
        throw new CloudException("response is null.");
    }

    int statusCode = response.code();
    ResponseBody responseBody;
    if (response.isSuccess()) {
        responseBody = response.body();
    } else {
        responseBody = response.errorBody();
    }
    if (statusCode != 200 && statusCode != 202 && statusCode != 204) {
        CloudException exception = new CloudException(statusCode + " is not a valid polling status code");
        exception.setResponse(response);
        if (responseBody != null) {
            exception.setBody((CloudError) mapperAdapter.deserialize(responseBody.string(), CloudError.class));
        }
        throw exception;
    }

    PollingState<T> pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(),
            resourceType);

    // Check provisioning state
    while (!AzureAsyncOperation.getTerminalStatuses().contains(pollingState.getStatus())) {
        Thread.sleep(pollingState.getDelayInMilliseconds());

        if (pollingState.getAzureAsyncOperationHeaderLink() != null
                && !pollingState.getAzureAsyncOperationHeaderLink().isEmpty()) {
            updateStateFromAzureAsyncOperationHeader(pollingState);
        } else if (pollingState.getLocationHeaderLink() != null
                && !pollingState.getLocationHeaderLink().isEmpty()) {
            updateStateFromLocationHeaderOnPostOrDelete(pollingState);
        } else {
            CloudException exception = new CloudException("No header in response");
            exception.setResponse(response);
            throw exception;
        }
    }

    // Check if operation failed
    if (AzureAsyncOperation.getFailedStatuses().contains(pollingState.getStatus())) {
        throw new CloudException("Async operation failed");
    }

    return new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse());
}

From source file:com.microsoft.azure.AzureClient.java

License:Open Source License

/**
 * Handles an initial response from a POST or DELETE operation response by polling
 * the status of the operation asynchronously, calling the user provided callback
 * when the operation terminates.//from w w  w .  j  a  va2 s.c  om
 *
 * @param response  the initial response from the POST or DELETE operation.
 * @param <T>       the return type of the caller.
 * @param resourceType the type of the resource.
 * @param callback  the user callback to call when operation terminates.
 * @return          the task describing the asynchronous polling.
 */
public <T> AsyncPollingTask<T> getPostOrDeleteResultAsync(Response<ResponseBody> response, Type resourceType,
        ServiceCallback<T> callback) {
    if (response == null) {
        callback.failure(new ServiceException("response is null."));
        return null;
    }

    int statusCode = response.code();
    ResponseBody responseBody;
    if (response.isSuccess()) {
        responseBody = response.body();
    } else {
        responseBody = response.errorBody();
    }
    if (statusCode != 200 && statusCode != 201 && statusCode != 202) {
        CloudException exception = new CloudException(statusCode + " is not a valid polling status code");
        exception.setResponse(response);
        try {
            if (responseBody != null) {
                exception.setBody(
                        (CloudError) mapperAdapter.deserialize(responseBody.string(), CloudError.class));
            }
        } catch (Exception e) {
            /* ignore serialization errors on top of service errors */ }
        callback.failure(exception);
        return null;
    }

    PollingState<T> pollingState;
    try {
        pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType);
    } catch (IOException e) {
        callback.failure(e);
        return null;
    }

    // Task runner will take it from here
    PostDeletePollingTask<T> task = new PostDeletePollingTask<>(pollingState, callback);
    executor.schedule(task, pollingState.getDelayInMilliseconds(), TimeUnit.MILLISECONDS);
    return task;
}

From source file:com.microsoft.rest.AzureClient.java

License:Open Source License

/**
 * Handles an initial response from a PUT or PATCH operation response by polling
 * the status of the operation until the long running operation terminates.
 *
 * @param response  the initial response from the PUT or PATCH operation.
 * @param <T>       the return type of the caller
 * @param resourceType the type of the resource
 * @return          the terminal response for the operation.
 * @throws CloudException REST exception
 * @throws InterruptedException interrupted exception
 * @throws IOException thrown by deserialization
 *///from w  w w . jav  a2 s  . c  o m
public <T> ServiceResponse<T> getPutOrPatchResult(Response<ResponseBody> response, Type resourceType)
        throws CloudException, InterruptedException, IOException {
    if (response == null) {
        throw new CloudException("response is null.");
    }

    int statusCode = response.code();
    ResponseBody responseBody;
    if (response.isSuccess()) {
        responseBody = response.body();
    } else {
        responseBody = response.errorBody();
    }
    if (statusCode != 200 && statusCode != 201 && statusCode != 202) {
        CloudException exception = new CloudException(statusCode + " is not a valid polling status code");
        exception.setResponse(response);
        if (responseBody != null) {
            exception.setBody(
                    (CloudError) new AzureJacksonUtils().deserialize(responseBody.string(), CloudError.class));
        }
        throw exception;
    }

    PollingState<T> pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(),
            resourceType);
    String url = response.raw().request().urlString();

    // Check provisioning state
    while (!AzureAsyncOperation.getTerminalStatuses().contains(pollingState.getStatus())) {
        Thread.sleep(pollingState.getDelayInMilliseconds());

        if (pollingState.getAzureAsyncOperationHeaderLink() != null
                && !pollingState.getAzureAsyncOperationHeaderLink().isEmpty()) {
            updateStateFromAzureAsyncOperationHeader(pollingState);
        } else if (pollingState.getLocationHeaderLink() != null
                && !pollingState.getLocationHeaderLink().isEmpty()) {
            updateStateFromLocationHeaderOnPut(pollingState);
        } else {
            updateStateFromGetResourceOperation(pollingState, url);
        }
    }

    if (AzureAsyncOperation.SUCCESS_STATUS.equals(pollingState.getStatus())
            && pollingState.getResource() == null) {
        updateStateFromGetResourceOperation(pollingState, url);
    }

    if (AzureAsyncOperation.getFailedStatuses().contains(pollingState.getStatus())) {
        throw new CloudException("Async operation failed");
    }

    return new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse());
}