Example usage for com.squareup.okhttp Response code

List of usage examples for com.squareup.okhttp Response code

Introduction

In this page you can find the example usage for com.squareup.okhttp Response code.

Prototype

int code

To view the source code for com.squareup.okhttp Response code.

Click Source Link

Usage

From source file:com.gzsll.downloads.DownloadThread.java

License:Apache License

/**
 * Check the HTTP response status and handle anything unusual (e.g. not
 * 200/206)./*from   w w w.j a v a2  s. com*/
 */
private void handleExceptionalStatus(State state, InnerState innerState, Response response)
        throws StopRequest, RetryDownload {
    int statusCode = response.code();
    if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
        handleServiceUnavailable(state, response);
    }
    if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) {
        handleRedirect(state, response, statusCode);
    }

    int expectedStatus = innerState.mContinuingDownload ? 206 : Downloads.STATUS_SUCCESS;
    if (statusCode != expectedStatus) {
        handleOtherStatus(state, innerState, statusCode);
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

/**
 * Ensure that the access token is still valid
 * Access token can be expired or revoked by user
 * Try to refresh the access token if it is expired
 *///from  w  w  w  .j  av  a 2 s  . co m
private void validateAccessToken() {
    Request request = getUserInfoRequest(mAccessToken);

    mHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
            if (mPrepareListener != null)
                mPrepareListener.onPrepareFail(e);
            Log.e(TAG, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful() && response.code() == 200) {
                if (mPrepareListener != null)
                    mPrepareListener.onPrepareSuccessful();
            } else {
                switch (response.code()) {
                case 401:
                    // unauthorized
                    refreshAccessToken();
                    break;
                default:
                    break;
                }
                Log.e(TAG, response.code() + ": " + response.body().string());
            }
        }
    });
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

/**
 * Try to get a fresh access token using the refresh token
 *///from  www  . j a v  a2  s. c  om
private void refreshAccessToken() {
    final String refreshToken = mCloudProvider.getUserData(mAccount, Authenticator.KEY_REFRESH_TOKEN);
    if (!TextUtils.isEmpty(refreshToken)) {
        Request request = new Request.Builder().url(TOKEN_URL).post(getRefreshTokenBody(refreshToken)).build();

        mHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());

                resetAccount();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    // convert string into json
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        Map<String, String> tokenInfo = extractAccessToken(jsonObject);
                        mCloudProvider.updateAccount(mAccount, tokenInfo);
                        mAccessToken = tokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
                        // validate again
                        validateAccessToken();
                    } catch (JSONException e) {
                        // no remedy
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                    }
                } else {
                    Log.e(TAG, response.code() + ": " + response.body().string());
                    resetAccount();
                }
            }
        });
    } else {
        resetAccount();
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized List<Object> exploreFolder(@NonNull CFolder folder, int offset)
        throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }/*  ww  w . j  a  v  a2s  .  com*/

    List<Object> list = new ArrayList<>();
    String folderId = folder.getId();
    Uri uri = Uri.parse(API_BASE_URL);
    String url = uri.buildUpon().appendEncodedPath("folders/" + folderId + "/items")
            .appendQueryParameter("limit", "500").appendQueryParameter("offset", String.valueOf(offset)).build()
            .toString();

    Request request = new Request.Builder().url(url)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            JSONObject jsonObject = new JSONObject(response.body().string());
            int total = jsonObject.getInt("total_count");
            // return null if no item found
            if (total == 0)
                return null;

            JSONArray entries = jsonObject.getJSONArray("entries");
            list.addAll(createFilteredItemsList(entries, folder));
            // suspect search result over 500 items
            if (total > 500 && total - list.size() > 0) {
                list.addAll(exploreFolder(folder, 500));
            }
            return list;
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized CFolder getFolderInfo(@NonNull String folderId) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }// w ww. ja  v a2 s  . c  om

    if (TextUtils.isEmpty(folderId))
        return null;

    Request request = new Request.Builder().url(API_BASE_URL + "/folders/" + folderId)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            // new file created
            JSONObject jsonObject = new JSONObject(response.body().string());
            return buildFolder(jsonObject);
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized CFolder createFolder(@NonNull String name, @Nullable CFolder parent)
        throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//w w w .  j a  va 2  s  .  c om
    // create parameter as json
    final JSONObject params = new JSONObject();
    try {
        params.put("name", name);
        params.put("parent", new JSONObject().put("id", parent != null ? parent.getId() : getRoot().getId()));
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }

    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return JSON;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8(params.toString());
        }
    };

    Request request = new Request.Builder().url(API_BASE_URL + "/folders")
            .header("Authorization", String.format("Bearer %s", mAccessToken)).post(body).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful() && response.code() == 201) {
            // new folder created
            return buildFolder(new JSONObject(response.body().string()));
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized CFolder renameFolder(@NonNull CFolder folder, String name) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }/* w ww .  j a  v a2s  . c o m*/

    // exit if root or same name
    if (folder.isRoot() || folder.getName().equals(name))
        return folder;

    // create parameter as json
    final JSONObject params = new JSONObject();
    try {
        params.put("name", name);
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }

    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return JSON;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8(params.toString());
        }
    };

    Request request = new Request.Builder().url(API_BASE_URL + "/folders/" + folder.getId())
            .header("Authorization", String.format("Bearer %s", mAccessToken)).put(body).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            // return folder object
            return buildFolder(new JSONObject(response.body().string()));
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized CFolder moveFolder(@NonNull CFolder folder, @Nullable CFolder parent)
        throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//w ww . j a v  a2 s  .  c o m

    // exit if root or same name
    if (folder.isRoot() || parent != null && folder.getId().equals(parent.getId()))
        return folder;

    // create parameter as json
    final JSONObject params = new JSONObject();
    try {
        params.put("parent", new JSONObject().put("id", parent != null ? parent.getId() : getRoot().getId()));
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }

    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return JSON;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8(params.toString());
        }
    };

    Request request = new Request.Builder().url(API_BASE_URL + "/folders/" + folder.getId())
            .header("Authorization", String.format("Bearer %s", mAccessToken)).put(body).build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            // return folder object
            return buildFolder(new JSONObject(response.body().string()));
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized void deleteFolder(@NonNull CFolder folder) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }/*w ww  .j  a va 2 s  .c o  m*/

    String folderId = folder.getId();
    Uri uri = Uri.parse(API_BASE_URL);
    String url = uri.buildUpon().appendEncodedPath("folders/" + folderId)
            .appendQueryParameter("recursive", "true").build().toString();

    Request request = new Request.Builder().url(url)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).delete().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            Log.d(TAG, "CFolder with the id: " + folderId + " deleted");
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

@Override
public synchronized CFile getFileInfo(@NonNull String fileId) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//from   w w  w . j  a  v  a 2 s .c  o  m

    if (TextUtils.isEmpty(fileId))
        return null;

    Request request = new Request.Builder().url(API_BASE_URL + "/files/" + fileId)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            // new file created
            JSONObject jsonObject = new JSONObject(response.body().string());
            return buildFile(jsonObject);
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}