Search in sources :

Example 16 with ANError

use of com.androidnetworking.error.ANError in project Fast-Android-Networking by amitshekhariitbhu.

the class OkHttpResponseTestActivity method downloadFile.

public void downloadFile(final View view) {
    String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP";
    AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip").setPriority(Priority.HIGH).setTag(this).build().setAnalyticsListener(new AnalyticsListener() {

        @Override
        public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {
            Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
            Log.d(TAG, " bytesSent : " + bytesSent);
            Log.d(TAG, " bytesReceived : " + bytesReceived);
            Log.d(TAG, " isFromCache : " + isFromCache);
        }
    }).setDownloadProgressListener(new DownloadProgressListener() {

        @Override
        public void onProgress(long bytesDownloaded, long totalBytes) {
            Log.d(TAG, "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes);
            Log.d(TAG, "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
        }
    }).startDownload(new DownloadListener() {

        @Override
        public void onDownloadComplete() {
            Log.d(TAG, "File download Completed");
            Log.d(TAG, "onDownloadComplete isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
        }

        @Override
        public void onError(ANError error) {
            if (error.getErrorCode() != 0) {
                // received ANError from server
                // error.getErrorCode() - the ANError code from server
                // error.getErrorBody() - the ANError body from server
                // error.getErrorDetail() - just an ANError detail
                Log.d(TAG, "onError errorCode : " + error.getErrorCode());
                Log.d(TAG, "onError errorBody : " + error.getErrorBody());
                Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
            } else {
                // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
            }
        }
    });
}
Also used : AnalyticsListener(com.androidnetworking.interfaces.AnalyticsListener) DownloadProgressListener(com.androidnetworking.interfaces.DownloadProgressListener) DownloadListener(com.androidnetworking.interfaces.DownloadListener) ANError(com.androidnetworking.error.ANError)

Example 17 with ANError

use of com.androidnetworking.error.ANError in project Fast-Android-Networking by amitshekhariitbhu.

the class InternalNetworking method performSimpleRequest.

public static Response performSimpleRequest(ANRequest request) throws ANError {
    Request okHttpRequest;
    Response okHttpResponse;
    try {
        Request.Builder builder = new Request.Builder().url(request.getUrl());
        addHeadersToRequestBuilder(builder, request);
        RequestBody requestBody = null;
        switch(request.getMethod()) {
            case GET:
                {
                    builder = builder.get();
                    break;
                }
            case POST:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.post(requestBody);
                    break;
                }
            case PUT:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.put(requestBody);
                    break;
                }
            case DELETE:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.delete(requestBody);
                    break;
                }
            case HEAD:
                {
                    builder = builder.head();
                    break;
                }
            case OPTIONS:
                {
                    builder = builder.method(ANConstants.OPTIONS, null);
                    break;
                }
            case PATCH:
                {
                    requestBody = request.getRequestBody();
                    builder = builder.patch(requestBody);
                    break;
                }
        }
        if (request.getCacheControl() != null) {
            builder.cacheControl(request.getCacheControl());
        }
        okHttpRequest = builder.build();
        if (request.getOkHttpClient() != null) {
            request.setCall(request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).build().newCall(okHttpRequest));
        } else {
            request.setCall(sHttpClient.newCall(okHttpRequest));
        }
        final long startTime = System.currentTimeMillis();
        final long startBytes = TrafficStats.getTotalRxBytes();
        okHttpResponse = request.getCall().execute();
        final long timeTaken = System.currentTimeMillis() - startTime;
        if (okHttpResponse.cacheResponse() == null) {
            final long finalBytes = TrafficStats.getTotalRxBytes();
            final long diffBytes;
            if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
                diffBytes = okHttpResponse.body().contentLength();
            } else {
                diffBytes = finalBytes - startBytes;
            }
            ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, okHttpResponse.body().contentLength(), false);
        } else if (request.getAnalyticsListener() != null) {
            if (okHttpResponse.networkResponse() == null) {
                Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, 0, 0, true);
            } else {
                Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, 0, true);
            }
        }
    } catch (IOException ioe) {
        throw new ANError(ioe);
    }
    return okHttpResponse;
}
Also used : Response(okhttp3.Response) ANRequest(com.androidnetworking.common.ANRequest) Request(okhttp3.Request) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) RequestBody(okhttp3.RequestBody)

Example 18 with ANError

use of com.androidnetworking.error.ANError in project Fast-Android-Networking by amitshekhariitbhu.

the class InternalNetworking method performDownloadRequest.

public static Response performDownloadRequest(final ANRequest request) throws ANError {
    Request okHttpRequest;
    Response okHttpResponse;
    try {
        Request.Builder builder = new Request.Builder().url(request.getUrl());
        addHeadersToRequestBuilder(builder, request);
        builder = builder.get();
        if (request.getCacheControl() != null) {
            builder.cacheControl(request.getCacheControl());
        }
        okHttpRequest = builder.build();
        OkHttpClient okHttpClient;
        if (request.getOkHttpClient() != null) {
            okHttpClient = request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).addNetworkInterceptor(new Interceptor() {

                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
                }
            }).build();
        } else {
            okHttpClient = sHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {

                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
                }
            }).build();
        }
        request.setCall(okHttpClient.newCall(okHttpRequest));
        final long startTime = System.currentTimeMillis();
        final long startBytes = TrafficStats.getTotalRxBytes();
        okHttpResponse = request.getCall().execute();
        Utils.saveFile(okHttpResponse, request.getDirPath(), request.getFileName());
        final long timeTaken = System.currentTimeMillis() - startTime;
        if (okHttpResponse.cacheResponse() == null) {
            final long finalBytes = TrafficStats.getTotalRxBytes();
            final long diffBytes;
            if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
                diffBytes = okHttpResponse.body().contentLength();
            } else {
                diffBytes = finalBytes - startBytes;
            }
            ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, okHttpResponse.body().contentLength(), false);
        } else if (request.getAnalyticsListener() != null) {
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, 0, true);
        }
    } catch (IOException ioe) {
        try {
            File destinationFile = new File(request.getDirPath() + File.separator + request.getFileName());
            if (destinationFile.exists()) {
                destinationFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ANError(ioe);
    }
    return okHttpResponse;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ANRequest(com.androidnetworking.common.ANRequest) Request(okhttp3.Request) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) IOException(java.io.IOException) Response(okhttp3.Response) HttpLoggingInterceptor(com.androidnetworking.interceptors.HttpLoggingInterceptor) Interceptor(okhttp3.Interceptor) File(java.io.File)

Example 19 with ANError

use of com.androidnetworking.error.ANError in project Fast-Android-Networking by amitshekhariitbhu.

the class SynchronousCall method executeSimpleRequest.

private static <T> ANResponse<T> executeSimpleRequest(ANRequest request) {
    Response okHttpResponse = null;
    try {
        okHttpResponse = InternalNetworking.performSimpleRequest(request);
        if (okHttpResponse == null) {
            return new ANResponse<>(Utils.getErrorForConnection(new ANError()));
        }
        if (request.getResponseAs() == ResponseType.OK_HTTP_RESPONSE) {
            ANResponse response = new ANResponse(okHttpResponse);
            response.setOkHttpResponse(okHttpResponse);
            return response;
        }
        if (okHttpResponse.code() >= 400) {
            ANResponse response = new ANResponse<>(Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code()));
            response.setOkHttpResponse(okHttpResponse);
            return response;
        }
        ANResponse response = request.parseResponse(okHttpResponse);
        response.setOkHttpResponse(okHttpResponse);
        return response;
    } catch (ANError se) {
        return new ANResponse<>(Utils.getErrorForConnection(new ANError(se)));
    } catch (Exception e) {
        return new ANResponse<>(Utils.getErrorForConnection(new ANError(e)));
    } finally {
        SourceCloseUtil.close(okHttpResponse, request);
    }
}
Also used : ANResponse(com.androidnetworking.common.ANResponse) Response(okhttp3.Response) ANError(com.androidnetworking.error.ANError) ANResponse(com.androidnetworking.common.ANResponse)

Example 20 with ANError

use of com.androidnetworking.error.ANError in project Fast-Android-Networking by amitshekhariitbhu.

the class SynchronousCall method executeDownloadRequest.

private static <T> ANResponse<T> executeDownloadRequest(ANRequest request) {
    Response okHttpResponse;
    try {
        okHttpResponse = InternalNetworking.performDownloadRequest(request);
        if (okHttpResponse == null) {
            return new ANResponse<>(Utils.getErrorForConnection(new ANError()));
        }
        if (okHttpResponse.code() >= 400) {
            ANResponse response = new ANResponse<>(Utils.getErrorForServerResponse(new ANError(okHttpResponse), request, okHttpResponse.code()));
            response.setOkHttpResponse(okHttpResponse);
            return response;
        }
        ANResponse response = new ANResponse(ANConstants.SUCCESS);
        response.setOkHttpResponse(okHttpResponse);
        return response;
    } catch (ANError se) {
        return new ANResponse<>(Utils.getErrorForConnection(new ANError(se)));
    } catch (Exception e) {
        return new ANResponse<>(Utils.getErrorForConnection(new ANError(e)));
    }
}
Also used : ANResponse(com.androidnetworking.common.ANResponse) Response(okhttp3.Response) ANError(com.androidnetworking.error.ANError) ANResponse(com.androidnetworking.common.ANResponse)

Aggregations

ANError (com.androidnetworking.error.ANError)214 MockResponse (okhttp3.mockwebserver.MockResponse)148 CountDownLatch (java.util.concurrent.CountDownLatch)129 AtomicReference (java.util.concurrent.atomic.AtomicReference)129 Response (okhttp3.Response)77 ANResponse (com.androidnetworking.common.ANResponse)74 JSONObject (org.json.JSONObject)50 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)42 List (java.util.List)31 User (com.androidnetworking.model.User)30 Disposable (io.reactivex.disposables.Disposable)30 JSONArray (org.json.JSONArray)29 ANRequest (com.androidnetworking.common.ANRequest)27 OkHttpResponseAndJSONObjectRequestListener (com.androidnetworking.interfaces.OkHttpResponseAndJSONObjectRequestListener)21 User (com.jacksonandroidnetworking.model.User)20 JSONException (org.json.JSONException)18 OkHttpResponseAndJSONArrayRequestListener (com.androidnetworking.interfaces.OkHttpResponseAndJSONArrayRequestListener)17 OkHttpResponseAndStringRequestListener (com.androidnetworking.interfaces.OkHttpResponseAndStringRequestListener)15 JSONObjectRequestListener (com.androidnetworking.interfaces.JSONObjectRequestListener)13 JSONArrayRequestListener (com.androidnetworking.interfaces.JSONArrayRequestListener)12