Example usage for com.squareup.okhttp Response request

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

Introduction

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

Prototype

Request request

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

Click Source Link

Usage

From source file:org.floens.chan.core.manager.ReplyManager.java

License:Open Source License

public void postDelete(final SavedReply reply, boolean onlyImageDelete, final DeleteListener listener) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder();
    formBuilder.add(Integer.toString(reply.no), "delete");
    if (onlyImageDelete) {
        formBuilder.add("onlyimgdel", "on");
    }/*from ww  w  .j  av a 2s  .com*/
    formBuilder.add("mode", "usrdel");
    formBuilder.add("pwd", reply.password);

    Request.Builder request = new Request.Builder().url(ChanUrls.getDeleteUrl(reply.board))
            .post(formBuilder.build());

    makeOkHttpCall(request, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            final DeleteResponse res = new DeleteResponse();
            res.isNetworkError = true;
            runUI(new Runnable() {
                @Override
                public void run() {
                    listener.onResponse(res);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                onFailure(response.request(), null);
                return;
            }
            String responseString = response.body().string();
            response.body().close();

            final DeleteResponse res = new DeleteResponse();
            res.responseData = responseString;

            if (responseString.contains("You must wait longer before deleting this post")) {
                res.isUserError = true;
                res.isTooSoonError = true;
            } else if (responseString.contains("Password incorrect")) {
                res.isUserError = true;
                res.isInvalidPassword = true;
            } else if (responseString.contains("You cannot delete a post this old")) {
                res.isUserError = true;
                res.isTooOldError = true;
            } else if (responseString.contains("Updating index")) {
                res.isSuccessful = true;
            }

            runUI(new Runnable() {
                @Override
                public void run() {
                    listener.onResponse(res);
                }
            });
        }
    });
}

From source file:org.sonar.runner.impl.ServerConnection.java

License:Open Source License

/**
 * @throws IOException           if connectivity error/timeout (network)
 * @throws IllegalStateException if HTTP code is different than 2xx
 *///from w  ww  . j ava2s.  com
private ResponseBody callUrl(String url) throws IOException, IllegalStateException {
    Request request = new Request.Builder().url(url).addHeader("User-Agent", userAgent).get().build();
    Response response = httpClient.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IllegalStateException(format("Status returned by url [%s] is not valid: [%s]",
                response.request().url(), response.code()));
    }
    return response.body();
}

From source file:org.xbmc.kore.jsonrpc.HostConnection.java

License:Open Source License

/**
 * Initializes this class OkHttpClient/* ww w  .  j  a va  2  s.co  m*/
 */
public OkHttpClient getOkHttpClient() {
    if (httpClient == null) {
        httpClient = new OkHttpClient();
        httpClient.setConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS);

        httpClient.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                if (TextUtils.isEmpty(hostInfo.getUsername()))
                    return null;

                String credential = Credentials.basic(hostInfo.getUsername(), hostInfo.getPassword());
                return response.request().newBuilder().header("Authorization", credential).build();
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }
    return httpClient;
}

From source file:pct.droid.base.providers.media.YTSProvider.java

License:Open Source License

/**
 * Fetch the list of movies from YTS/*from  w  w  w .j av a2 s. c  om*/
 *
 * @param currentList    Current shown list to be extended
 * @param requestBuilder Request to be executed
 * @param callback       Network callback
 * @return Call
 */
private Call fetchList(final ArrayList<Media> currentList, final Request.Builder requestBuilder,
        final Filters filters, final Callback callback) {
    requestBuilder.addHeader("Host", "xor.image.yt");
    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (generateFallback(requestBuilder)) {
                fetchList(currentList, requestBuilder, filters, callback);
            } else {
                callback.onFailure(e);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr;
                try {
                    responseStr = response.body().string();
                } catch (SocketException e) {
                    onFailure(response.request(), new IOException("Socket failed"));
                    return;
                }

                YTSReponse result;
                try {
                    result = mGson.fromJson(responseStr, YTSReponse.class);
                } catch (IllegalStateException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                } catch (JsonSyntaxException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                }

                if (result.status != null && result.status.equals("error")) {
                    callback.onFailure(new NetworkErrorException(result.status_message));
                } else if (result.data != null && ((result.data.get("movies") != null
                        && ((ArrayList<LinkedTreeMap<String, Object>>) result.data.get("movies")).size() <= 0)
                        || ((Double) result.data.get("movie_count")).intValue() <= currentList.size())) {
                    callback.onFailure(new NetworkErrorException("No movies found"));
                } else {
                    ArrayList<Media> formattedData = result.formatForPopcorn(currentList);
                    callback.onSuccess(filters, formattedData, true);
                    return;
                }
            }
            onFailure(response.request(), new IOException("Couldn't connect to YTS"));
        }
    });
}

From source file:pct.droid.base.providers.media.YTSProvider.java

License:Open Source License

private Call fetchDetail(final Request.Builder requestBuilder, final Callback callback) {
    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override//w w  w .ja va 2  s  .c  om
        public void onFailure(Request request, IOException e) {
            if (generateFallback(requestBuilder)) {
                fetchDetail(requestBuilder, callback);
            } else {
                callback.onFailure(e);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr;
                try {
                    responseStr = response.body().string();
                } catch (SocketException e) {
                    onFailure(response.request(), new IOException("Socket failed"));
                    return;
                }

                YTSReponse result;
                try {
                    result = mGson.fromJson(responseStr, YTSReponse.class);
                } catch (IllegalStateException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                } catch (JsonSyntaxException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                }

                if (result.status != null && result.status.equals("error")) {
                    callback.onFailure(new NetworkErrorException(result.status_message));
                } else {
                    final Movie movie = result.formatDetailForPopcorn();

                    TraktProvider traktProvider = new TraktProvider();

                    traktProvider.getMovieMeta(movie.imdbId, new MetaProvider.Callback() {
                        @Override
                        public void onResult(MetaProvider.MetaData metaData, Exception e) {
                            if (e == null) {
                                if (metaData.trailer != null) {
                                    movie.trailer = metaData.trailer;
                                }

                                if (metaData.certification != null) {
                                    movie.certification = metaData.certification;
                                }
                            }

                            final ArrayList<Media> returnData = new ArrayList<>();
                            returnData.add(movie);
                            callback.onSuccess(null, returnData, true);
                        }
                    });

                    return;
                }
            }
            onFailure(response.request(), new IOException("Couldn't connect to YTS"));
        }
    });
}

From source file:pct.droid.base.providers.subs.SubsProvider.java

License:Open Source License

/**
 * @param context      Context/* w  ww  .  j  av  a  2s.  c  o m*/
 * @param media        Media data
 * @param languageCode Code of language
 * @param callback     Network callback
 * @return Call
 */
public static Call download(final Context context, final Media media, final String languageCode,
        final com.squareup.okhttp.Callback callback) {
    OkHttpClient client = PopcornApplication.getHttpClient();
    if (media.subtitles != null && media.subtitles.containsKey(languageCode)) {
        try {
            Request request = new Request.Builder().url(media.subtitles.get(languageCode)).build();
            Call call = client.newCall(request);

            final File subsDirectory = getStorageLocation(context);
            final String fileName = media.videoId + "-" + languageCode;
            final File srtPath = new File(subsDirectory, fileName + ".srt");

            if (srtPath.exists()) {
                callback.onResponse(null);
                return call;
            }

            call.enqueue(new com.squareup.okhttp.Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    callback.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    if (response.isSuccessful()) {
                        InputStream inputStream = null;
                        boolean failure = false;
                        try {

                            subsDirectory.mkdirs();
                            if (srtPath.exists()) {
                                File to = new File(subsDirectory, "temp" + System.currentTimeMillis());
                                srtPath.renameTo(to);
                                to.delete();
                            }

                            inputStream = response.body().byteStream();
                            String urlString = response.request().urlString();

                            if (urlString.contains(".zip") || urlString.contains(".gz")) {
                                SubsProvider.unpack(inputStream, srtPath, languageCode);
                            } else if (SubsProvider.isSubFormat(urlString)) {
                                parseFormatAndSave(urlString, srtPath, languageCode, inputStream);
                            } else {
                                callback.onFailure(response.request(),
                                        new IOException("FatalParsingException"));
                                failure = true;
                            }
                        } catch (FatalParsingException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), new IOException("FatalParsingException"));
                            failure = true;
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), e);
                            failure = true;
                        } catch (IOException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), e);
                            failure = true;
                        } finally {
                            if (inputStream != null)
                                inputStream.close();

                            if (!failure)
                                callback.onResponse(response);
                        }
                    } else {
                        callback.onFailure(response.request(), new IOException("Unknown error"));
                    }
                }
            });

            return call;
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    callback.onFailure(null, new IOException("Wrong media"));
    return null;
}

From source file:retrofit.RetrofitError.java

License:Apache License

public static RetrofitError networkError(Response response, IOException exception) {
    response = response.newBuilder().body(null).build(); // Remove any body.
    return new RetrofitError(exception.getMessage(), response.request().urlString(), null, null, null,
            Kind.NETWORK, exception);//from w  w w  .  j  a  va 2s .  co m
}

From source file:retrofit.RetrofitError.java

License:Apache License

public static RetrofitError httpError(Response response, Converter converter, Type successType) {
    String message = response.code() + " " + response.message();
    return new RetrofitError(message, response.request().urlString(), response, converter, successType,
            Kind.HTTP, null);/*from  ww w. j  av  a2  s.  c om*/
}

From source file:retrofit.RetrofitError.java

License:Apache License

public static RetrofitError unexpectedError(Response response, Throwable exception) {
    response = response.newBuilder().body(null).build(); // Remove any body.
    return new RetrofitError(exception.getMessage(), response.request().urlString(), response, null, null,
            Kind.UNEXPECTED, exception);
}

From source file:uk.co.craiggarrigan.dvsacancellationfinder.CancellationService.java

private void printResponse(Response response) throws IOException {

    Log.d(SVC, "Response for " + response.request().urlString());

    BufferedReader r;//w  w  w  .j a  v  a2  s .  c om
    String s;
    r = new BufferedReader(new InputStreamReader(response.body().byteStream()));
    while ((s = r.readLine()) != null) {
        Log.d(SVC, s);
    }
}