Example usage for com.squareup.okhttp Response isSuccessful

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

Introduction

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

Prototype

public boolean isSuccessful() 

Source Link

Document

Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

Usage

From source file:com.mummyding.app.leisure.database.cache.cache.DailyCache.java

License:Open Source License

private void loadOld(String date, final List<StoryBean> oldList, final List<StoryBean> newList) {
    Request.Builder builder = new Request.Builder();
    builder.url(DailyApi.daily_old_url + date);
    Request request = builder.build();
    HttpUtil.enqueue(request, new Callback() {
        @Override/*from  ww  w. j  ava2  s.com*/
        public void onFailure(Request request, IOException e) {
            mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful() == false) {
                mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
                return;
            }
            String res = response.body().string();

            ArrayList<Integer> collectionIDs = new ArrayList<Integer>();
            for (int i = 0; i < oldList.size(); i++) {
                if (oldList.get(i).isCollected() == 1) {
                    collectionIDs.add(oldList.get(i).getId());
                }
            }

            // clear old data
            mList.clear();

            Gson gson = new Gson();
            StoryBean[] storyBeans = (gson.fromJson(res, DailyBean.class)).getStories();
            for (StoryBean storyBeen : storyBeans) {
                newList.add(storyBeen);
            }

            for (StoryBean storyBean : newList) {
                mList.add(storyBean);
            }

            // setCollection flag
            for (Integer id : collectionIDs) {
                for (int i = 0; i < mList.size(); i++) {
                    if (id.equals(mList.get(i).getId())) {
                        mList.get(i).setCollected(1);
                    }
                }
            }

            // notify
            mHandler.sendEmptyMessage(CONSTANT.ID_SUCCESS);
        }
    });
}

From source file:com.mummyding.app.leisure.database.cache.cache.NewsCache.java

License:Open Source License

@Override
public void load() {
    Request.Builder builder = new Request.Builder();
    builder.url(mUrl);//from w w w .  j  a v a2 s  .  co  m
    Request request = builder.build();
    HttpUtil.enqueue(request, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {
            if (response.isSuccessful() == false) {
                mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
                return;
            }
            InputStream is = new ByteArrayInputStream(
                    response.body().string().getBytes(Charset.forName("UTF-8")));
            try {
                ArrayList<String> collectionTitles = new ArrayList<String>();
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getIs_collected() == 1) {
                        collectionTitles.add(mList.get(i).getTitle());
                    }
                }

                mList.clear();
                mList.addAll(SAXNewsParse.parse(is));
                for (String title : collectionTitles) {
                    for (int i = 0; i < mList.size(); i++) {
                        if (title.equals(mList.get(i).getTitle())) {
                            mList.get(i).setIs_collected(1);
                        }
                    }
                }
                is.close();
                mHandler.sendEmptyMessage(CONSTANT.ID_SUCCESS);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

}

From source file:com.mummyding.app.leisure.database.cache.cache.ReadingCache.java

License:Open Source License

@Override
public void load() {
    Utils.DLog("from net reading size: " + mList.size());
    for (int i = 0; i < mUrls.length; i++) {
        String url = mUrls[i];/*from  w  w w  .j  a va  2s .  c o m*/
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        Request request = builder.build();

        HttpUtil.enqueue(request, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
            }

            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                if (response.isSuccessful() == false) {
                    mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
                    return;
                }
                ArrayList<String> collectionTitles = new ArrayList<String>();
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getIs_collected() == 1) {
                        collectionTitles.add(mList.get(i).getTitle());
                    }
                }
                Gson gson = new Gson();
                BookBean[] bookBeans = gson.fromJson(response.body().string(), ReadingBean.class).getBooks();
                mList.clear();
                for (BookBean bookBean : bookBeans) {
                    mList.add(bookBean);
                }

                for (String title : collectionTitles) {
                    for (int i = 0; i < mList.size(); i++) {
                        if (title.equals(mList.get(i).getTitle())) {
                            mList.get(i).setIs_collected(1);
                        }
                    }
                }
                mHandler.sendEmptyMessage(CONSTANT.ID_SUCCESS);
            }
        });
    }

}

From source file:com.mummyding.app.leisure.database.cache.cache.ScienceCache.java

License:Open Source License

@Override
public void load() {
    Request.Builder builder = new Request.Builder();
    builder.url(mUrl);/*  ww  w.j av  a 2 s .c  om*/
    Request request = builder.build();
    HttpUtil.enqueue(request, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {
            if (response.isSuccessful() == false) {
                mHandler.sendEmptyMessage(CONSTANT.ID_FAILURE);
                return;
            }

            ArrayList<String> collectionTitles = new ArrayList<String>();
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).getIs_collected() == 1) {
                    collectionTitles.add(mList.get(i).getTitle());
                }
            }

            mList.clear();
            Gson gson = new Gson();
            ArticleBean[] articleBeans = (gson.fromJson(response.body().string(), ScienceBean.class))
                    .getResult();
            for (ArticleBean articleBean : articleBeans) {
                mList.add(articleBean);
            }

            for (String title : collectionTitles) {
                for (int i = 0; i < mList.size(); i++) {
                    if (title.equals(mList.get(i).getTitle())) {
                        mList.get(i).setIs_collected(1);
                    }
                }
            }
            mHandler.sendEmptyMessage(CONSTANT.ID_SUCCESS);
        }
    });

}

From source file:com.mycelium.lt.api.LtApiClient.java

License:Apache License

private Response getConnectionAndSendRequest(LtRequest request, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();

    // Figure what our current endpoint is. On errors we fail over until we
    // are back at the initial endpoint
    HttpEndpoint initialEndpoint = getEndpoint();
    while (true) {
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {//  ww w .  j  a va2  s . c  o m
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("LT connecting to " + serverEndpoint.getBaseUrl() + " ("
                    + _serverEndpoints.getCurrentEndpointIndex() + ")");

            // configure TimeOuts
            client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);

            Stopwatch callDuration = Stopwatch.createStarted();
            // build request
            final String toSend = getPostBody(request);
            Request rq = new Request.Builder()
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(request.toString()).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format("LtApi %s finished (%dms)", request.toString(),
                    callDuration.elapsed(TimeUnit.MILLISECONDS)));

            // Check for status code 2XX
            if (response.isSuccessful()) {
                if (serverEndpoint instanceof FeedbackEndpoint) {
                    ((FeedbackEndpoint) serverEndpoint).onSuccess();
                }
                return response;
            } else {
                // If the status code is not 200 we cycle to the next server
                logError(String.format("Local Trader server request for class %s returned HTTP status code %d",
                        request.getClass().toString(), response.code()));
            }

        } catch (IOException e) {
            logError("getConnectionAndSendRequest failed IO exception.");
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }

        // We had an IO exception or a bad status, fail over and try again
        _serverEndpoints.switchToNextEndpoint();
        // Check if we are back at the initial endpoint, in which case we have
        // to give up
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }
    }
}

From source file:com.mycelium.wapi.api.WapiClient.java

License:Apache License

/**
 * Attempt to connect and send to a URL in our list of URLS, if it fails try
 * the next until we have cycled through all URLs. timeout.
 *//*  w w w  .java2 s.  c  om*/
private Response getConnectionAndSendRequestWithTimeout(Object request, String function, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();
    while (true) {
        // currently active server-endpoint
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("Connecting to " + serverEndpoint.getBaseUrl() + " ("
                    + _serverEndpoints.getCurrentEndpointIndex() + ")");

            // configure TimeOuts
            client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);

            Stopwatch callDuration = Stopwatch.createStarted();
            // build request
            final String toSend = getPostBody(request);
            Request rq = new Request.Builder().addHeader(MYCELIUM_VERSION_HEADER, versionCode)
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(WapiConst.WAPI_BASE_PATH, function).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format("Wapi %s finished (%dms)", function,
                    callDuration.elapsed(TimeUnit.MILLISECONDS)));

            // Check for status code 2XX
            if (response.isSuccessful()) {
                if (serverEndpoint instanceof FeedbackEndpoint) {
                    ((FeedbackEndpoint) serverEndpoint).onSuccess();
                }
                return response;
            } else {
                // If the status code is not 200 we cycle to the next server
                logError(String.format("Http call to %s failed with %d %s", function, response.code(),
                        response.message()));
                // throw...
            }
        } catch (IOException e) {
            logError("IOException when sending request " + function, e);
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }
        // Try the next server
        _serverEndpoints.switchToNextEndpoint();
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }

    }
}

From source file:com.netflix.spinnaker.clouddriver.artifacts.maven.MavenArtifactCredentials.java

License:Apache License

@Override
public InputStream download(Artifact artifact) {
    try {//from w  w  w  . ja v a 2s.c  om
        DefaultArtifact requestedArtifact = new DefaultArtifact(artifact.getReference());
        String artifactPath = resolveVersion(requestedArtifact)
                .map(version -> repositoryLayout.getLocation(withVersion(requestedArtifact, version), false))
                .map(URI::getPath)
                .orElseThrow(() -> new IllegalStateException("No versions matching constraint '"
                        + artifact.getVersion() + "' for '" + artifact.getReference() + "'"));

        Request artifactRequest = new Request.Builder().url(account.getRepositoryUrl() + "/" + artifactPath)
                .get().build();

        Response artifactResponse = okHttpClient.newCall(artifactRequest).execute();
        if (artifactResponse.isSuccessful()) {
            return artifactResponse.body().byteStream();
        }
        throw new IllegalStateException("Unable to download artifact with reference '" + artifact.getReference()
                + "'. HTTP " + artifactResponse.code());
    } catch (IOException | ArtifactDownloadException e) {
        throw new IllegalStateException(
                "Unable to download artifact with reference '" + artifact.getReference() + "'", e);
    }
}

From source file:com.netflix.spinnaker.clouddriver.artifacts.maven.MavenArtifactCredentials.java

License:Apache License

private Optional<String> resolveVersion(org.eclipse.aether.artifact.Artifact artifact) {
    try {// w  w w. j ava2 s . c  om
        String metadataPath = metadataUri(artifact).getPath();
        Request metadataRequest = new Request.Builder().url(account.getRepositoryUrl() + "/" + metadataPath)
                .get().build();
        Response response = okHttpClient.newCall(metadataRequest).execute();

        if (response.isSuccessful()) {
            VersionScheme versionScheme = new GenericVersionScheme();
            VersionConstraint versionConstraint = versionScheme.parseVersionConstraint(artifact.getVersion());
            Versioning versioning = new MetadataXpp3Reader().read(response.body().byteStream(), false)
                    .getVersioning();

            if (isRelease(artifact)) {
                return Optional.ofNullable(versioning.getRelease());
            } else if (isLatestSnapshot(artifact)) {
                return resolveVersion(withVersion(artifact, versioning.getLatest()));
            } else if (isLatest(artifact)) {
                String latestVersion = versioning.getLatest();
                return latestVersion != null && latestVersion.endsWith("-SNAPSHOT")
                        ? resolveVersion(withVersion(artifact, latestVersion))
                        : Optional.ofNullable(latestVersion);
            } else if (artifact.getVersion().endsWith("-SNAPSHOT")) {
                String requestedClassifier = artifact.getClassifier() == null ? "" : artifact.getClassifier();
                return versioning.getSnapshotVersions().stream()
                        .filter(v -> v.getClassifier().equals(requestedClassifier))
                        .map(SnapshotVersion::getVersion).findFirst();
            } else {
                return versioning.getVersions().stream().map(v -> {
                    try {
                        return versionScheme.parseVersion(v);
                    } catch (InvalidVersionSpecificationException e) {
                        throw new ArtifactDownloadException(e);
                    }
                }).filter(versionConstraint::containsVersion).max(Version::compareTo).map(Version::toString);
            }
        } else {
            throw new IOException("Unsuccessful response retrieving maven-metadata.xml " + response.code());
        }
    } catch (IOException | XmlPullParserException | InvalidVersionSpecificationException e) {
        throw new ArtifactDownloadException(e);
    }
}

From source file:com.nizlumina.utils.WebUnitMaster.java

License:Open Source License

/**
 * Get a string object from response body of the given url. For threaded calls, use {@link #enqueueGetString}
 *
 * @param url The URL for the request//from w w w . j a va2  s.  c o m
 * @return The body in a string object. Returns null on failure.
 * @throws java.io.IOException
 */
public synchronized String getString(final String url) throws IOException {
    final Response response = executeSync(url);

    if (response != null && response.isSuccessful()) {
        return response.body().string();
    }
    return null;
}

From source file:com.nizlumina.utils.WebUnitMaster.java

License:Open Source License

/**
 * Invoke methods on a returned Stream via a Callable
 *
 * @param url      The URL for the request
 * @param callable The callable instance to apply on the fully received inputstream
 * @throws java.io.IOException/*from  w  w w  . jav  a  2  s .co  m*/
 */
public synchronized void invokeOnStream(final String url, final StreamCallable callable) throws IOException {
    final Response response = executeSync(url);

    if (response != null && response.isSuccessful()) {
        callable.onStreamReceived(response.body().byteStream());
    }
}