Search in sources :

Example 1 with ANRequest

use of com.androidnetworking.common.ANRequest in project Fast-Android-Networking by amitshekhariitbhu.

the class ANImageLoader method get.

public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ImageView.ScaleType scaleType) {
    throwIfNotOnMainThread();
    final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
    Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
    if (cachedBitmap != null) {
        ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
        imageListener.onResponse(container, true);
        return container;
    }
    ImageContainer imageContainer = new ImageContainer(null, requestUrl, cacheKey, imageListener);
    imageListener.onResponse(imageContainer, true);
    BatchedImageRequest request = mInFlightRequests.get(cacheKey);
    if (request != null) {
        request.addContainer(imageContainer);
        return imageContainer;
    }
    ANRequest newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey);
    mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer));
    return imageContainer;
}
Also used : ANRequest(com.androidnetworking.common.ANRequest) Bitmap(android.graphics.Bitmap)

Example 2 with ANRequest

use of com.androidnetworking.common.ANRequest 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 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) Request(okhttp3.Request) ANRequest(com.androidnetworking.common.ANRequest) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) RequestBody(okhttp3.RequestBody)

Example 3 with ANRequest

use of com.androidnetworking.common.ANRequest 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) Request(okhttp3.Request) ANRequest(com.androidnetworking.common.ANRequest) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) IOException(java.io.IOException) Response(okhttp3.Response) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(com.androidnetworking.interceptors.HttpLoggingInterceptor) File(java.io.File)

Example 4 with ANRequest

use of com.androidnetworking.common.ANRequest in project Fast-Android-Networking by amitshekhariitbhu.

the class ApiTestActivity method checkSynchronousCall.

public void checkSynchronousCall(View view) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            String url = "http://www.colorado.edu/conflict/peace/download/peace_problem.ZIP";
            ANRequest requestOne = AndroidNetworking.download(url, Utils.getRootDirPath(getApplicationContext()), "file1.zip").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()));
                }
            });
            ANResponse<String> responseOne = requestOne.executeForDownload();
            if (responseOne.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : download success");
                Log.d(TAG, "checkSynchronousCall : download result " + responseOne.getResult());
                Response response = responseOne.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : download failed");
                Utils.logError(TAG, responseOne.getError());
            }
            ANRequest requestTwo = AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0").addQueryParameter("limit", "3").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);
                }
            });
            ANResponse<List<User>> responseTwo = requestTwo.executeForObjectList(User.class);
            if (responseTwo.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : response success");
                List<User> users = responseTwo.getResult();
                Log.d(TAG, "userList size : " + users.size());
                for (User user : users) {
                    Log.d(TAG, "id : " + user.id);
                    Log.d(TAG, "firstname : " + user.firstname);
                    Log.d(TAG, "lastname : " + user.lastname);
                }
                Response response = responseTwo.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : response failed");
                Utils.logError(TAG, responseTwo.getError());
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("firstname", "Rohit");
                jsonObject.put("lastname", "Kumar");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            ANRequest requestThree = AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER).addJSONObjectBody(jsonObject).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);
                }
            });
            ANResponse<JSONObject> responseThree = requestThree.executeForJSONObject();
            if (responseThree.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse success");
                JSONObject jsonObjectFinal = responseThree.getResult();
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse result " + jsonObjectFinal.toString());
                Response response = responseThree.getOkHttpResponse();
                Log.d(TAG, "checkSynchronousCall : headers : " + response.headers().toString());
            } else {
                Log.d(TAG, "checkSynchronousCall : jsonObjectANResponse failed");
                Utils.logError(TAG, responseThree.getError());
            }
            ANRequest requestFour = AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY).addPathParameter("pageNumber", "0").addQueryParameter("limit", "3").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);
                }
            });
            ANResponse<Response> responseFour = requestFour.executeForOkHttpResponse();
            if (responseFour.isSuccess()) {
                Log.d(TAG, "checkSynchronousCall : okHttpResponse success");
                Response okHttpResponse = responseFour.getResult();
                if (okHttpResponse != null) {
                    if (okHttpResponse.isSuccessful()) {
                        Log.d(TAG, "response is successful");
                        try {
                            Log.d(TAG, "response : " + okHttpResponse.body().source().readUtf8());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.d(TAG, "response is not successful");
                    }
                } else {
                    Log.d(TAG, "response is null");
                }
            } else {
                Log.d(TAG, "checkSynchronousCall : okHttpResponse failed");
                Utils.logError(TAG, responseFour.getError());
            }
        }
    }).start();
}
Also used : ANRequest(com.androidnetworking.common.ANRequest) AnalyticsListener(com.androidnetworking.interfaces.AnalyticsListener) User(com.networking.model.User) DownloadProgressListener(com.androidnetworking.interfaces.DownloadProgressListener) JSONException(org.json.JSONException) IOException(java.io.IOException) Response(okhttp3.Response) ANResponse(com.androidnetworking.common.ANResponse) JSONObject(org.json.JSONObject) List(java.util.List)

Example 5 with ANRequest

use of com.androidnetworking.common.ANRequest in project Fast-Android-Networking by amitshekhariitbhu.

the class ApiTest method testSynchronousGetRequest.

@SuppressWarnings("unchecked")
public void testSynchronousGetRequest() throws InterruptedException {
    server.enqueue(new MockResponse().setBody("getResponse"));
    ANRequest request = AndroidNetworking.get(server.url("/").toString()).build();
    ANResponse<String> response = request.executeForString();
    assertEquals("getResponse", response.getResult());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) ANRequest(com.androidnetworking.common.ANRequest)

Aggregations

ANRequest (com.androidnetworking.common.ANRequest)13 ANError (com.androidnetworking.error.ANError)6 Response (okhttp3.Response)6 IOException (java.io.IOException)5 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)4 JSONObject (org.json.JSONObject)4 ANResponse (com.androidnetworking.common.ANResponse)3 Request (okhttp3.Request)3 Bitmap (android.graphics.Bitmap)2 DownloadProgressListener (com.androidnetworking.interfaces.DownloadProgressListener)2 User (com.networking.model.User)2 List (java.util.List)2 RequestBody (okhttp3.RequestBody)2 MockResponse (okhttp3.mockwebserver.MockResponse)2 JSONException (org.json.JSONException)2 HttpLoggingInterceptor (com.androidnetworking.interceptors.HttpLoggingInterceptor)1 BitmapRequestListener (com.androidnetworking.interfaces.BitmapRequestListener)1 JSONObjectRequestListener (com.androidnetworking.interfaces.JSONObjectRequestListener)1 OkHttpResponseAndJSONObjectRequestListener (com.androidnetworking.interfaces.OkHttpResponseAndJSONObjectRequestListener)1 File (java.io.File)1