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:cloud.artik.api.UsersApi.java

License:Apache License

private com.squareup.okhttp.Call getUserDevicesCall(String userId, Integer offset, Integer count,
        Boolean includeProperties, final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = null;

    // verify the required parameter 'userId' is set
    if (userId == null) {
        throw new ApiException("Missing the required parameter 'userId' when calling getUserDevices(Async)");
    }//from   w  w  w  .j a v a2  s  .  c  o m

    // create path and map variables
    String localVarPath = "/users/{userId}/devices".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "userId" + "\\}", apiClient.escapeString(userId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    if (offset != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "offset", offset));
    if (count != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "count", count));
    if (includeProperties != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "includeProperties", includeProperties));

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "artikcloud_oauth" };
    return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:cloud.artik.api.UsersApi.java

License:Apache License

private com.squareup.okhttp.Call getUserPropertiesCall(String userId, String aid,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = null;

    // verify the required parameter 'userId' is set
    if (userId == null) {
        throw new ApiException("Missing the required parameter 'userId' when calling getUserProperties(Async)");
    }/*from  w w w  . j a v a2s  .  c o  m*/

    // create path and map variables
    String localVarPath = "/users/{userId}/properties".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "userId" + "\\}", apiClient.escapeString(userId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    if (aid != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "aid", aid));

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "artikcloud_oauth" };
    return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:cloud.artik.api.UsersApi.java

License:Apache License

private com.squareup.okhttp.Call getUserRulesCall(String userId, Boolean excludeDisabled, Integer count,
        Integer offset, final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = null;

    // verify the required parameter 'userId' is set
    if (userId == null) {
        throw new ApiException("Missing the required parameter 'userId' when calling getUserRules(Async)");
    }//w  ww  .  j av a 2  s . c o  m

    // create path and map variables
    String localVarPath = "/users/{userId}/rules".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "userId" + "\\}", apiClient.escapeString(userId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    if (excludeDisabled != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "excludeDisabled", excludeDisabled));
    if (count != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "count", count));
    if (offset != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "offset", offset));

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "artikcloud_oauth" };
    return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:cloud.artik.api.UsersApi.java

License:Apache License

private com.squareup.okhttp.Call updateUserPropertiesCall(String userId, AppProperties properties, String aid,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = properties;

    // verify the required parameter 'userId' is set
    if (userId == null) {
        throw new ApiException(
                "Missing the required parameter 'userId' when calling updateUserProperties(Async)");
    }/* ww w . jav a 2  s.  c  o m*/

    // verify the required parameter 'properties' is set
    if (properties == null) {
        throw new ApiException(
                "Missing the required parameter 'properties' when calling updateUserProperties(Async)");
    }

    // create path and map variables
    String localVarPath = "/users/{userId}/properties".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "userId" + "\\}", apiClient.escapeString(userId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    if (aid != null)
        localVarQueryParams.addAll(apiClient.parameterToPairs("", "aid", aid));

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = { "application/json" };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "artikcloud_oauth" };
    return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams,
            localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:cn.com.canon.darwin.modules.service.api.interceptor.HttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }//from www . ja  va 2s .  c  o  m

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();

    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        //            if (hasRequestBody) {
        //                // Request body headers are only present when installed as a
        //                // network interceptor. Force
        //                // them to be included (when available) so there values are
        //                // known.
        //                if (requestBody.contentType() != null) {
        //                    logger.log("Content-Type: " + requestBody.contentType());
        //                }
        //                if (requestBody.contentLength() != -1) {
        //                    logger.log("Content-Length: " + requestBody.contentLength());
        //                }
        //            }

        //            Headers headers = request.headers();
        //            for (int i = 0, count = headers.size(); i < count; i++) {
        //                String name = headers.name(i);
        //                // Skip headers from the request body as they are explicitly
        //                // logged above.
        //                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
        //                    logger.log(name + ": " + headers.value(i));
        //                }
        //            }

        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength()
                        + "-byte body omitted)");
            }
        }
    }

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');

    //        if (logHeaders) {
    //            Headers headers = response.headers();
    //            for (int i = 0, count = headers.size(); i < count; i++) {
    //                logger.log(headers.name(i) + ": " + headers.value(i));
    //            }
    //
    if (!logBody || !HttpEngine.hasBody(response)) {
        logger.log("<-- END HTTP");
    } else if (bodyEncoded(response.headers())) {
        logger.log("<-- END HTTP (encoded body omitted)");
    } else {
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                logger.log("");
                logger.log("Couldn't decode the response body; charset is likely malformed.");
                logger.log("<-- END HTTP");

                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            logger.log("");
            logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
            return response;
        }
        if (contentLength != 0) {
            logger.log("");
            logger.log(buffer.clone().readString(charset));
        }
        logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
    }
    //        }

    return response;
}

From source file:cn.com.crcement.oa.base.download.helper.ProgressHelper.java

License:Apache License

/**
 * OkHttpClient//from   w  w  w .j a v a2  s .c  o  m
 * 
 * @param client
 *            OkHttpClient
 * @param progressListener
 *            ?
 * @return ?OkHttpClientclone
 */
public static OkHttpClient addProgressResponseListener(OkHttpClient client,
        final ProgressListener progressListener) {
    // 
    OkHttpClient clone = client.clone();
    // 
    clone.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            // 
            Response originalResponse = chain.proceed(chain.request());
            // ?
            return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
        }
    });
    return clone;
}

From source file:cn.edu.zafu.coreprogress.helper.ProgressHelper.java

License:Apache License

/**
 * OkHttpClient//from w  w  w  .  j a  v a2s  .co m
 * @param client OkHttpClient
 * @param progressListener ?
 * @return ?OkHttpClientclone
 */
public static OkHttpClient addProgressResponseListener(OkHttpClient client,
        final ProgressListener progressListener) {
    //
    OkHttpClient clone = client.clone();
    //
    clone.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //
            Response originalResponse = chain.proceed(chain.request());
            //?
            return originalResponse.newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
        }
    });
    return clone;
}

From source file:cn.edu.zafu.news.ui.main.NewsFragment.java

License:Apache License

private void refreshData() {
    isRefreshing = true;/*w ww  .  ja v a  2  s . com*/
    page = 1;
    OkHttpClient client = NewsOkHttpClient.getInstance();
    final Request request = new Request.Builder().url(category.getUrl() + page).build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            handler.sendEmptyMessage(REFRESH_ERROR);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            NewsParser newsParser = new NewsParser();
            String str = response.body().string();
            if (max == 0) {
                getMaxPage(str);
            }
            list.clear();
            list.addAll(newsParser.convert(str));
            handler.sendEmptyMessage(REFRESH);
        }
    });

}

From source file:cn.edu.zafu.news.ui.main.NewsFragment.java

License:Apache License

private synchronized void loadMore() {
    isLoadingMore = true;//from w  w  w . j a  v a2 s .c  o  m
    if (page >= max) {
        Toast.makeText(getActivity(), "?", Toast.LENGTH_LONG).show();
        return;
    }
    page++;
    OkHttpClient client = NewsOkHttpClient.getInstance();
    final Request request = new Request.Builder().url(category.getUrl() + page).build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            handler.sendEmptyMessage(LOADMORE_ERROR);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            NewsParser newsParser = new NewsParser();
            list.addAll(newsParser.convert(response.body().string()));
            handler.sendEmptyMessage(LOADMORE);
        }
    });
}

From source file:cn.finalteam.okhttpfinal.dm.DownloadHttpTask.java

License:Apache License

private int request() {
    String url = mDownloadInfo.getUrl();
    int resultCode = RESULT_SUCCESS;
    long startPos = 0;
    String fileName = FileUtils.getUrlFileName(url);
    File file = new File(mDownloadInfo.getTargetFolder(), fileName);
    if (StringUtils.isEmpty(mDownloadInfo.getTargetPath())) {
        mDownloadInfo.setTargetPath(file.getAbsolutePath());
    }/* w  ww.j  a  v a 2  s. c om*/
    if (file.exists()) {
        startPos = file.length();
    } else {
        try {
            boolean b = file.createNewFile();
            if (!b) {
                resultCode = RESULT_OTHER_ERROR;
                Logger.e("create new File failure file=" + file.getAbsolutePath());
                return resultCode;
            }
        } catch (IOException e) {
            Logger.e(e + " file=" + file.getAbsolutePath());
            resultCode = RESULT_OTHER_ERROR;
            return resultCode;
        }
    }

    //
    try {
        mProgressReportingRandomAccessFile = new ProgressReportingRandomAccessFile(file, "rw", startPos);
    } catch (FileNotFoundException e) {
        Logger.e(e);
        resultCode = RESULT_OTHER_ERROR;
        return resultCode;
    }
    Request request = new Request.Builder().url(url).header("RANGE", "bytes=" + startPos + "-")//httpRANGE
            .build();

    //
    Response response = null;
    try {
        response = mOkHttpClient.newCall(request).execute();
    } catch (IOException e) {
        Logger.e(e);
        resultCode = RESULT_OTHER_ERROR;
        return resultCode;
    }

    if (response == null || !response.isSuccessful()) {//??
        if (response != null) {
            Logger.e("~ code=" + response.code() + "url=" + url);
        }
        resultCode = RESULT_NET_ERROR;
    } else {

        try {
            InputStream inputStream = response.body().byteStream();
            try {
                long totalLength = response.body().contentLength();
                if (mDownloadInfo.getTotalLength() == 0l) {
                    mDownloadInfo.setTotalLength(totalLength);
                }

                //??
                if (startPos > mDownloadInfo.getTotalLength()) {
                    FileUtils.deleteFile(mDownloadInfo.getTargetPath());
                    mDownloadInfo.setProgress(0);
                    mDownloadInfo.setDownloadLength(0);
                    mDownloadInfo.setTotalLength(0);
                    return resultCode;
                }

                if (startPos == mDownloadInfo.getTotalLength() && startPos > 0) {
                    publishProgress(100);
                    return resultCode;
                }

                //?
                int bytesCopied = download(inputStream, mProgressReportingRandomAccessFile);
                if (((startPos + bytesCopied) != mDownloadInfo.getTotalLength()) || mInterrupt) {
                    //
                    resultCode = RESULT_OTHER_ERROR;
                    return resultCode;
                }
            } catch (Exception e) {
                e.printStackTrace();
                resultCode = RESULT_OTHER_ERROR;
                return resultCode;
            }
        } catch (IOException e) {
            e.printStackTrace();
            resultCode = RESULT_OTHER_ERROR;
            return resultCode;
        }
    }
    return resultCode;
}