Example usage for com.squareup.okhttp Response body

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

Introduction

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

Prototype

ResponseBody body

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

Click Source Link

Usage

From source file:com.heroiclabs.sdk.android.util.http.RetryInterceptor.java

License:Apache License

/**
 * Recursive helper method that catches IOExceptions and calls itself again if the maximum number of allowed
 * retries has not yet been exceeded./* ww w .j  a va2s.  c o  m*/
 *
 * @param chain The request chain.
 * @param count The number of the current attempt.
 * @return The response forwarded by the chain.
 * @throws IOException if even after all retries the request fails.
 */
private Response attemptRequest(final Chain chain, final int count) throws IOException {
    try {
        final Request request = chain.request();
        final Response response = chain.proceed(request);

        // Treat blank 504 responses as network issues.
        if (response.code() == HttpURLConnection.HTTP_GATEWAY_TIMEOUT
                && response.body().contentLength() == 0l) {
            throw new IOException("Unexpected 504 responses status");
        }

        return response;
    } catch (final IOException e) {
        if (count < maxAttempts) {
            try {
                // Wait between 100 and 200 milliseconds, inclusive.
                Thread.sleep(random.nextInt(101) + 100);
            } catch (final InterruptedException ex) {
                // Don't care.
            }

            return attemptRequest(chain, count + 1);
        } else {
            throw e;
        }
    }
}

From source file:com.hippo.network.DownloadClient.java

License:Apache License

public static boolean execute(DownloadRequest request) {
    OnDownloadListener listener = request.mListener;
    OkHttpClient okHttpClient = request.mOkHttpClient;

    UniFile uniFile = null;//from  ww  w .  j  av a2  s. co m
    OutputStreamPipe osPipe = null;
    try {
        Call call = okHttpClient.newCall(new GoodRequestBuilder(request.mUrl).build());
        request.mCall = call;

        // Listener
        if (listener != null) {
            listener.onStartDownloading();
        }

        Response response = call.execute();
        ResponseBody body = response.body();

        // Check response code
        int responseCode = response.code();
        if (responseCode >= 400) {
            throw new ResponseCodeException(responseCode);
        }

        osPipe = request.mOSPipe;
        if (osPipe == null) {
            String extension;
            String name;

            String dispositionFilename = getFilenameFromContentDisposition(
                    response.header("Content-Disposition"));
            if (dispositionFilename != null) {
                name = FileUtils.getNameFromFilename(dispositionFilename);
                extension = FileUtils.getExtensionFromFilename(dispositionFilename);
            } else {
                name = Utilities.getNameFromUrl(request.mUrl);
                extension = Utilities.getExtensionFromMimeType(response.header("Content-Type"));
                if (extension == null) {
                    extension = MimeTypeMap.getFileExtensionFromUrl(request.mUrl);
                }
            }

            String filename;
            if (listener != null) {
                filename = listener.onFixname(name, extension, request.mFilename);
            } else {
                filename = request.mFilename;
            }
            request.mFilename = filename;

            // Use Temp filename
            uniFile = request.mDir.createFile(FileUtils.ensureFilename(filename + ".download"));
            if (uniFile == null) {
                // Listener
                if (listener != null) {
                    listener.onFailed(new IOException("Can't create file " + filename));
                }
                return false;
            }
            osPipe = new UniFileOutputStreamPipe(uniFile);
        }
        osPipe.obtain();

        long contentLength = body.contentLength();

        // Listener
        if (listener != null) {
            listener.onConnect(contentLength);
        }

        long receivedSize = transferData(body.byteStream(), osPipe.open(), listener);

        if (contentLength > 0 && contentLength != receivedSize) {
            throw new IOException(
                    "contentLength is " + contentLength + ", but receivedSize is " + receivedSize);
        }

        // Rename
        if (uniFile != null && request.mFilename != null) {
            uniFile.renameTo(request.mFilename);
        }

        // Listener
        if (listener != null) {
            listener.onSucceed();
        }
        return true;
    } catch (Exception e) {
        // remove download failed file
        if (uniFile != null) {
            uniFile.delete();
        }

        if (listener != null) {
            listener.onFailed(e);
        }
        return false;
    } finally {
        if (osPipe != null) {
            osPipe.close();
            osPipe.release();
        }
    }
}

From source file:com.hippo.nimingban.client.ac.ACEngine.java

License:Apache License

public static Boolean doGetCookie(Call call) throws Exception {
    String body = null;//from  w  w w  .ja v  a 2s .c om
    try {
        Response response = call.execute();
        ResponseUtils.storeCookies(response);
        body = response.body().string();

        if (!"\"ok\"".equals(body)) {
            throw new NMBException(ACSite.getInstance(), UNKNOWN);
        }

        return true;
    } catch (Exception e) {
        throwException(call, body, e);
        throw e;
    }
}

From source file:com.hippo.nimingban.client.ac.ACEngine.java

License:Apache License

public static List<CommonPost> doGetCommonPosts(Call call) throws Exception {
    String body = null;//w w  w . ja v a 2s.c  o  m
    try {
        Response response = call.execute();
        body = response.body().string();

        List<CommonPost> result = JSON.parseArray(body, CommonPost.class);
        if (result == null) {
            throw new NMBException(ACSite.getInstance(), "Can't parse json when getForumList");
        }
        return result;
    } catch (Exception e) {
        throwException(call, body, e);
        throw e;
    }
}

From source file:com.hippo.nimingban.client.ac.ACEngine.java

License:Apache License

public static List<ACForumGroup> doGetForumList(Call call) throws Exception {
    String body = null;/*  ww  w .j a v a  2  s  .  c  o  m*/
    try {
        Response response = call.execute();
        body = response.body().string();

        List<ACForumGroup> result = JSON.parseArray(body, ACForumGroup.class);
        if (result == null) {
            throw new NMBException(ACSite.getInstance(), "Can't parse json when getForumList");
        }
        return result;
    } catch (Exception e) {
        throwException(call, body, e);
        throw e;
    }
}

From source file:com.hippo.nimingban.client.ac.ACEngine.java

License:Apache License

public static List<Post> doGetPostList(Call call) throws Exception {
    String body = null;/*from   w  ww  .  ja  va2 s  . c  o m*/
    try {
        Response response = call.execute();
        body = response.body().string();
        List<ACPost> acPosts = JSON.parseArray(body, ACPost.class);
        if (acPosts == null) {
            throw new NMBException(ACSite.getInstance(), "Can't parse json when getPostList");
        }

        List<Post> result = new ArrayList<>(acPosts.size());
        for (ACPost acPost : acPosts) {
            if (acPost != null) {
                acPost.generateSelfAndReplies(ACSite.getInstance());
                result.add(acPost);
            }
        }

        return result;
    } catch (Exception e) {
        throwException(call, body, e);
        throw e;
    }
}

From source file:com.hippo.nimingban.client.ac.ACEngine.java

License:Apache License

public static Pair<Post, List<Reply>> doGetPost(Call call) throws Exception {
    String body = null;//w  ww  .j  a va2 s  .  com
    try {
        Response response = call.execute();
        body = response.body().string();
        ACPost acPost = JSON.parseObject(body, ACPost.class);
        if (acPost == null) {
            throw new NMBException(ACSite.getInstance(), "Can't parse json when getPost");
        }
        acPost.generateSelfAndReplies(ACSite.getInstance());
        return new Pair<Post, List<Reply>>(acPost, new ArrayList<Reply>(acPost.replys));
    } catch (Exception e) {
        throwException(call, body, e);
        throw e;
    }
}

From source file:com.hippo.nimingban.client.ac.ACEngine.java

License:Apache License

public static Reply doGetReference(Call call) throws Exception {
    String body = null;/*w  ww.j  a  va  2  s  .  com*/
    try {
        Response response = call.execute();
        body = response.body().string();

        ACReference reference = new ACReference();
        Document doc = Jsoup.parse(body, ACUrl.HOST + "/");
        List<Element> elements = doc.getAllElements();
        for (Element element : elements) {
            String className = element.className();
            if ("h-threads-item-reply h-threads-item-ref".equals(className)) {
                reference.id = element.attr("data-threads-id");
            } else if ("h-threads-img-a".equals(className)) {
                reference.image = element.attr("href");
            } else if ("h-threads-img".equals(className)) {
                reference.thumb = element.attr("src");
            } else if ("h-threads-info-title".equals(className)) {
                reference.title = element.text();
            } else if ("h-threads-info-email".equals(className)) {
                // TODO email or user ?
                reference.user = element.text();
            } else if ("h-threads-info-createdat".equals(className)) {
                reference.time = element.text();
            } else if ("h-threads-info-uid".equals(className)) {
                String user = element.text();
                if (user.startsWith("ID:")) {
                    reference.userId = user.substring(3);
                } else {
                    reference.userId = user;
                }
                reference.admin = element.childNodeSize() > 1;
            } else if ("h-threads-info-id".equals(className)) {
                String href = element.attr("href");
                if (href.startsWith("/t/")) {
                    int index = href.indexOf('?');
                    if (index >= 0) {
                        reference.postId = href.substring(3, index);
                    } else {
                        reference.postId = href.substring(3);
                    }
                }
            } else if ("h-threads-content".equals(className)) {
                reference.content = element.html();
            }
        }

        reference.generate(ACSite.getInstance());

        return reference;
    } catch (Exception e) {
        throwException(call, body, e);
        throw e;
    }
}

From source file:com.hippo.nimingban.client.ac.ACEngine.java

License:Apache License

public static Void doReply(Call call) throws Exception {
    String body = null;//from   w w w.  j  a  va 2 s . co  m
    try {
        Response response = call.execute();
        ResponseUtils.storeCookies(response);
        body = response.body().string();

        try {
            JSONObject jo = JSON.parseObject(body);
            if (jo.getBoolean("success")) {
                return null;
            } else {
                throw new NMBException(ACSite.getInstance(), jo.getString("msg"));
            }
        } catch (Exception e) {
            if (body.contains("class=\"success\"")) {
                return null;
            } else {
                throw e;
            }
        }
    } catch (Exception e) {
        throwException(call, body, e);
        throw e;
    }
}

From source file:com.hippo.nimingban.client.ac.ACEngine.java

License:Apache License

public static List<Post> doGetFeed(Call call) throws Exception {
    String body = null;/*w w  w.  j a  v a 2  s. c om*/
    try {
        Response response = call.execute();
        body = response.body().string();

        List<ACFeed> acFeeds = JSON.parseArray(body, ACFeed.class);

        if (acFeeds == null) {
            throw new NMBException(ACSite.getInstance(), "Can't parse json when getPostList");
        }

        List<Post> result = new ArrayList<>(acFeeds.size());
        for (ACFeed feed : acFeeds) {
            if (feed != null) {
                feed.generate(ACSite.getInstance());
                result.add(feed);
            }
        }

        return result;
    } catch (Exception e) {
        throwException(call, body, e);
        throw e;
    }
}