🚀 A Complete Fast Android Networking Library that also supports HTTP/2 🚀

Overview

Fast Android Networking Library

Build Status Mindorks Mindorks Community Mindorks Android Store API Download Open Source Love License

About Fast Android Networking Library

Fast Android Networking Library is a powerful library for doing any type of networking in Android applications which is made on top of OkHttp Networking Layer.

Fast Android Networking Library takes care of each and everything. So you don't have to do anything, just make request and listen for the response.

Why use Fast Android Networking ?

  • Recent removal of HttpClient in Android Marshmallow(Android M) made other networking libraries obsolete.
  • No other single library does each and everything like making request, downloading any type of file, uploading file, loading image from network in ImageView, etc. There are some libraries but they are outdated.
  • No other library provides simple interface for doing all types of things in networking like setting priority, cancelling, etc.
  • As it uses Okio , No more GC overhead in android applications. Okio is made to handle GC overhead while allocating memory. Okio does some clever things to save CPU and memory.
  • It uses OkHttp , more importantly it supports HTTP/2.

RxJava2 Support, check here.

RxJava2 + Fast Android Networking + Dagger2 with MVP Architecture Project, Check here

Another awesome library for debugging databases and shared preferences, Check here

Learn to build a ride-sharing Android app like Uber, Lyft, Check here

Find this project useful ? ❤️

  • Support it by clicking the button on the upper right of this page. ✌️

For full details, visit the documentation on our web site :

Requirements

Fast Android Networking Library can be included in any Android application.

Fast Android Networking Library supports Android 2.3 (Gingerbread) and later.

Using Fast Android Networking Library in your application

Add this in your build.gradle

implementation 'com.amitshekhar.android:android-networking:1.0.2'

Do not forget to add internet permission in manifest if already not present

<uses-permission android:name="android.permission.INTERNET" />

Then initialize it in onCreate() Method of application class :

AndroidNetworking.initialize(getApplicationContext());

Initializing it with some customization , as it uses OkHttp as networking layer, you can pass custom okHttpClient while initializing it.

// Adding an Network Interceptor for Debugging purpose :
OkHttpClient okHttpClient = new OkHttpClient() .newBuilder()
                        .addNetworkInterceptor(new StethoInterceptor())
                        .build();
AndroidNetworking.initialize(getApplicationContext(),okHttpClient);                        

Using the Fast Android Networking with Jackson Parser

implementation 'com.amitshekhar.android:jackson-android-networking:1.0.2'
// Then set the JacksonParserFactory like below
AndroidNetworking.setParserFactory(new JacksonParserFactory());

Making a GET Request

AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                 .addPathParameter("pageNumber", "0")
                 .addQueryParameter("limit", "3")
                 .addHeaders("token", "1234")
                 .setTag("test")
                 .setPriority(Priority.LOW)
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });                

Making a POST Request

AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser")
                 .addBodyParameter("firstname", "Amit")
                 .addBodyParameter("lastname", "Shekhar")
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });

You can also post java object, json, file, etc in POST request like this.

User user = new User();
user.firstname = "Amit";
user.lastname = "Shekhar";

AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser")
                 .addBodyParameter(user) // posting java object
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });


JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("firstname", "Amit");
    jsonObject.put("lastname", "Shekhar");
} catch (JSONException e) {
  e.printStackTrace();
}
       
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser")
                 .addJSONObjectBody(jsonObject) // posting json
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });
                
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile")
                 .addFileBody(file) // posting any type of file
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });               

Using it with your own JAVA Object - JSON Parser

/*--------------Example One -> Getting the userList----------------*/
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                .addPathParameter("pageNumber", "0")
                .addQueryParameter("limit", "3")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .getAsObjectList(User.class, new ParsedRequestListener<List<User>>() {
                    @Override
                    public void onResponse(List<User> users) {
                      // do anything with response
                      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);
                      }
                    }
                    @Override
                    public void onError(ANError anError) {
                     // handle error
                    }
                });
/*--------------Example Two -> Getting an user----------------*/
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}")
                .addPathParameter("userId", "1")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .getAsObject(User.class, new ParsedRequestListener<User>() {
                     @Override
                     public void onResponse(User user) {
                        // do anything with response
                        Log.d(TAG, "id : " + user.id);
                        Log.d(TAG, "firstname : " + user.firstname);
                        Log.d(TAG, "lastname : " + user.lastname);
                     }
                     @Override
                     public void onError(ANError anError) {
                        // handle error
                     }
                 }); 
/*-- Note : YourObject.class, getAsObject and getAsObjectList are important here --*/              

Downloading a file from server

AndroidNetworking.download(url,dirPath,fileName)
                 .setTag("downloadTest")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                      // do anything with progress  
                    }
                 })
                 .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                      // do anything after completion
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error    
                    }
                });                 

Uploading a file to server

AndroidNetworking.upload(url)
                 .addMultipartFile("image",file)    
                 .addMultipartParameter("key","value")
                 .setTag("uploadTest")
                 .setPriority(Priority.HIGH)
                 .build()
                 .setUploadProgressListener(new UploadProgressListener() {
                    @Override
                    public void onProgress(long bytesUploaded, long totalBytes) {
                      // do anything with progress 
                    }
                 })
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response                
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error 
                    }
                 }); 

Getting Response and completion in an another thread executor

(Note : Error and Progress will always be returned in main thread of application)

AndroidNetworking.upload(url)
                 .addMultipartFile("image",file)  
                 .addMultipartParameter("key","value")  
                 .setTag("uploadTest")
                 .setPriority(Priority.HIGH)
                 .build()
                 .setExecutor(Executors.newSingleThreadExecutor()) // setting an executor to get response or completion on that executor thread
                 .setUploadProgressListener(new UploadProgressListener() {
                    @Override
                    public void onProgress(long bytesUploaded, long totalBytes) {
                      // do anything with progress 
                    }
                 })
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // below code will be executed in the executor provided
                      // do anything with response                
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error 
                    }
                 }); 

Setting a Percentage Threshold For Not Cancelling the request if it has completed the given threshold

AndroidNetworking.download(url,dirPath,fileName)
                 .setTag("downloadTest")
                 .setPriority(Priority.MEDIUM)
                 .setPercentageThresholdForCancelling(50) // even if at the time of cancelling it will not cancel if 50% 
                 .build()                                 // downloading is done.But can be cancalled with forceCancel.
                 .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                      // do anything with progress  
                    }
                 })
                 .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                      // do anything after completion
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error    
                    }
                });   

Cancelling a request.

Any request with a given tag can be cancelled. Just do like this.

AndroidNetworking.cancel("tag"); // All the requests with the given tag will be cancelled.
AndroidNetworking.forceCancel("tag");  // All the requests with the given tag will be cancelled , even if any percent threshold is
                                       // set , it will be cancelled forcefully. 
AndroidNetworking.cancelAll(); // All the requests will be cancelled.  
AndroidNetworking.forceCancelAll(); // All the requests will be cancelled , even if any percent threshold is
                               // set , it will be cancelled forcefully.                           

Loading image from network into ImageView

      <com.androidnetworking.widget.ANImageView
          android:id="@+id/imageView"
          android:layout_width="100dp"
          android:layout_height="100dp"
          android:layout_gravity="center" />
          
      imageView.setDefaultImageResId(R.drawable.default);
      imageView.setErrorImageResId(R.drawable.error);
      imageView.setImageUrl(imageUrl);          

Getting Bitmap from url with some specified parameters

AndroidNetworking.get(imageUrl)
                 .setTag("imageRequestTag")
                 .setPriority(Priority.MEDIUM)
                 .setBitmapMaxHeight(100)
                 .setBitmapMaxWidth(100)
                 .setBitmapConfig(Bitmap.Config.ARGB_8888)
                 .build()
                 .getAsBitmap(new BitmapRequestListener() {
                    @Override
                    public void onResponse(Bitmap bitmap) {
                    // do anything with bitmap
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });

Error Code Handling

public void onError(ANError error) {
   if (error.getErrorCode() != 0) {
        // received error from server
        // error.getErrorCode() - the error code from server
        // error.getErrorBody() - the error body from server
        // error.getErrorDetail() - just an error detail
        Log.d(TAG, "onError errorCode : " + error.getErrorCode());
        Log.d(TAG, "onError errorBody : " + error.getErrorBody());
        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
        // get parsed error object (If ApiError is your class)
        ApiError apiError = error.getErrorAsObject(ApiError.class);
   } else {
        // error.getErrorDetail() : connectionError, parseError, requestCancelledError
        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
   }
}

Remove Bitmap from cache or clear cache

AndroidNetworking.evictBitmap(key); // remove a bitmap with key from LruCache
AndroidNetworking.evictAllBitmap(); // clear LruCache

Prefetch a request (so that it can return from cache when required at instant)

AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                .addPathParameter("pageNumber", "0")
                .addQueryParameter("limit", "30")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .prefetch();

Customizing OkHttpClient for a particular request

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .addInterceptor(new GzipRequestInterceptor())
                .build();
                
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                 .addPathParameter("pageNumber", "0")
                 .addQueryParameter("limit", "3")
                 .addHeaders("token", "1234")
                 .setTag("test")
                 .setPriority(Priority.LOW)
                 .setOkHttpClient(okHttpClient) // passing a custom okHttpClient 
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                    // handle error
                    }
                });

Making a conditional request (Building a request)

ANRequest.GetRequestBuilder getRequestBuilder = new ANRequest.GetRequestBuilder(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER);
               
if(isHeaderRequired){
 getRequestBuilder.addHeaders("token", "1234");
}

if(executorRequired){
 getRequestBuilder.setExecutor(Executors.newSingleThreadExecutor());
}
               
ANRequest anRequest = getRequestBuilder.build();       
                 
anRequest.getAsJSONObject(new JSONObjectRequestListener() {
    @Override
    public void onResponse(JSONObject response) {
      // do anything with response
    }
    @Override
    public void onError(ANError error) {
      // handle error
    }
});

ConnectionClass Listener to get current network quality and bandwidth

// Adding Listener
AndroidNetworking.setConnectionQualityChangeListener(new ConnectionQualityChangeListener() {
            @Override
            public void onChange(ConnectionQuality currentConnectionQuality, int currentBandwidth) {
              // do something on change in connectionQuality
            }
        });
        
// Removing Listener   
AndroidNetworking.removeConnectionQualityChangeListener();

// Getting current ConnectionQuality
ConnectionQuality connectionQuality = AndroidNetworking.getCurrentConnectionQuality();
if(connectionQuality == ConnectionQuality.EXCELLENT) {
  // do something
} else if (connectionQuality == ConnectionQuality.POOR) {
  // do something
} else if (connectionQuality == ConnectionQuality.UNKNOWN) {
  // do something
}
// Getting current bandwidth
int currentBandwidth = AndroidNetworking.getCurrentBandwidth(); // Note : if (currentBandwidth == 0) : means UNKNOWN

Getting Analytics of a request by setting AnalyticsListener on that

AndroidNetworking.download(url,dirPath,fileName)
                 .setTag("downloadTest")
                 .setPriority(Priority.MEDIUM)
                 .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) {
                      // do anything with progress  
                    }
                 })
                 .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                      // do anything after completion
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error    
                    }
                });  
Note : If bytesSent or bytesReceived is -1 , it means it is unknown                

Getting OkHttpResponse in Response

AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}")
                .addPathParameter("userId", "1")
                .setTag(this)
                .setPriority(Priority.LOW)
                .setUserAgent("getAnUser")
                .build()
                .getAsOkHttpResponseAndParsed(new TypeToken<User>() {
                }, new OkHttpResponseAndParsedRequestListener<User>() {
                    @Override
                    public void onResponse(Response okHttpResponse, User user) {
                      // do anything with okHttpResponse and user
                    }
                    @Override
                    public void onError(ANError anError) {
                      // handle error
                    }
                });

Making Synchronous Request

ANRequest request = AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                        .addPathParameter("pageNumber", "0")
                        .addQueryParameter("limit", "3")
                        .build();
ANResponse<List<User>> response = request.executeForObjectList(User.class);
if (response.isSuccess()) {
   List<User> users = responseTwo.getResult();
} else {
   //handle error
}                                        

How caching works ?

  • First of all the server must send cache-control in header so that is starts working.
  • Response will be cached on the basis of cache-control max-age,max-stale.
  • If internet is connected and the age is NOT expired it will return from cache.
  • If internet is connected and the age is expired and if server returns 304(NOT MODIFIED) it will return from cache.
  • If internet is NOT connected if you are using getResponseOnlyIfCached() - it will return from cache even it date is expired.
  • If internet is NOT connected , if you are NOT using getResponseOnlyIfCached() - it will NOT return anything.
  • If you are using getResponseOnlyFromNetwork() , it will only return response after validation from server.
  • If cache-control is set, it will work according to the max-age,max-stale returned from server.
  • If internet is NOT connected only way to get cache Response is by using getResponseOnlyIfCached().

Enabling Logging

AndroidNetworking.enableLogging(); // simply enable logging
AndroidNetworking.enableLogging(LEVEL.HEADERS); // enabling logging with level

Enabling GZIP From Client to Server

// Enabling GZIP for Request (Not needed if your server doesn't support GZIP Compression), anyway responses 
// from server are automatically unGzipped if required. So enable it only if you need your request to be 
// Gzipped before sending to server(Make sure your server support GZIP Compression).
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .addInterceptor(new GzipRequestInterceptor())
                .build();
AndroidNetworking.initialize(getApplicationContext(),okHttpClient);                

IMPORTANT NOTE

  • Use IMMEDIATE Priority with caution - use is at appropriate place only when 1 or 2 (at max 2)IMMEDIATE request is required at instant.Otherwise use HIGH Priority.

  • Known Bug : As present if you are using GZIP Interceptor from client to server, Upload progress is not working perfectly in Multipart.

    If you are using Proguard with Gradle build system (which is usually the case), you don't have to do anything. The appropriate Proguard rules will be automatically applied. If you still need the rules applied in proguard-rules.pro, it is as follows:

    -dontwarn okio.**
    

Fast Android Networking Library supports

  • Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH
  • Fast Android Networking Library supports downloading any type of file
  • Fast Android Networking Library supports uploading any type of file (supports multipart upload)
  • Fast Android Networking Library supports cancelling a request
  • Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)
  • Fast Android Networking Library supports RxJava

As it uses OkHttp as a networking layer, it supports:

  • Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket
  • Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available)
  • Transparent GZIP shrinks download sizes
  • Fast Android Networking Library supports response caching which avoids the network completely for repeat requests

Difference over other Networking Library

  • In Fast Android Networking Library, OkHttpClient can be customized for every request easily — like timeout customization, etc. for each request.
  • As Fast Android Networking Library uses OkHttp and Okio, it is faster.
  • Single library for all type of networking.
  • Supports RxJava, RxJava2 -> Check here
  • Current bandwidth and connection quality can be obtained to decide logic of code.
  • Executor can be passed to any request to get the response in another thread.
  • Complete analytics of any request can be obtained.
  • All types of customization are possible.
  • Immediate Request really is immediate now.
  • Prefetching of any request can be done so that it gives instant data when required from the cache.
  • Proper request canceling.
  • Prevents cancellation of a request if it’s completed more than a specific threshold percentage.
  • A simple interface to make any type of request.
  • Proper Response Caching — which leads to reduced bandwidth usage.

TODO

  • Integration with other library
  • And of course many many features and bug fixes

CREDITS

Check out Mindorks awesome open source projects here

Contact - Let's become friend

License

   Copyright (C) 2016 Amit Shekhar
   Copyright (C) 2011 Android Open Source Project

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Contributing to Fast Android Networking

All pull requests are welcome, make sure to follow the contribution guidelines when you submit pull request.

Comments
  • Upload method not working

    Upload method not working

    AndroidNetworking.upload(getString(R.string.base_url) + getString(R.string.account) + "/" + getString(R.string.image)) .addMultipartFile("profile_image", new File(filePath)) .addHeaders(Headers.BaseHeader.getHeaders()) .addMultipartParameter("customer_id", userId) .setTag("updateProfileImage") .setPriority(Priority.HIGH) .build() .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { imageView.progress((int) ((bytesUploaded / totalBytes) * 100)); } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse: " + response.toString()); imageView.progress(100); BaseModel baseModel = getGson().fromJson(response.toString(), BaseModel.class); if (baseModel.isSuccess()) { imageView.showContent(baseModel.getData()); } else { imageView.showError(baseModel.getError()); }

                        }
    
                        @Override
                        public void onError(ANError error) {
                            Log.d(TAG, "onError: " + error.getErrorDetail());
                            imageView.progress(0);
                            imageView.showError(error.getErrorDetail() + "\n" + error.getErrorCode());
                        }
                    });
    
    opened by a-najar 39
  • How to use cache from Fast Android Networking

    How to use cache from Fast Android Networking

    i try to use cache request response from Fast Android Networking for 'POST' And 'GET' Request But I cant find any method to handle it! Is it possible to read response from cache? how i can handle it? Does it works when device is offline ?

    question 
    opened by HosseinKurd 26
  • Upload an image using PUT method instead of POST (MultiPartBuilder)

    Upload an image using PUT method instead of POST (MultiPartBuilder)

    Hi, I need to upload an image using PUT method but ANRequest mMethod property is set to POST in the contructor for MultiPartBuilder parameter;

    public ANRequest(MultiPartBuilder builder) { this.mRequestType = RequestType.MULTIPART; this.mMethod = Method.POST; ... }

    ¿How can I solve this?

    Thanks in advance. Antonio

    opened by adesousabarroso 18
  • Network on main thread

    Network on main thread

    hi, i am using the below code to get synchronous call, but got network on main thread error

    ANRequest request = AndroidNetworking.get(getResources().getString(R.string.server_url_user_mgmt_services) + "GetUserAuthorizationToken?eload_number={eloadnum}") .addHeaders("Content-Type", "application/json") .addHeaders("Authorization", CommonMethods.getSecurityHeader(OTP.this)) .addPathParameter("eloadnum", user.getUserIdentifier()) .build(); ANResponse response = request.executeForParsed(new TypeToken() {}); if (response.isSuccess()) { JSONObject obj = response.getResult(); try { boolean isValidUser = obj.getBoolean("isSuccessful"); if (isValidUser) { if (!obj.getString("Token").isEmpty()) { randomString = obj.getString("Token"); } else { randomString = null; } } } catch (JSONException e) { e.printStackTrace(); } } else { ANError error = response.getError(); // Handle Error Toast.makeText(OTP.this, "Some error occured!\nTry Again", Toast.LENGTH_SHORT).show(); }

    question 
    opened by mohsin1122 18
  • OAuth2.0 integration

    OAuth2.0 integration

    Hi, any plan to integrate OAuth2.0 functionalities?
    It would be nice if the library automagically manage login and token related task (get, refresh, etc). So, once the client is authenticated, authenticate header will be added on every API call and if expired, automatically renewed (with Password Grant Type)

    enhancement 
    opened by SimoneCarnio 17
  • Json Parsing error

    Json Parsing error

    I need to parse this JSON with as minimum code as possible. How can i achieve this?

    SAMPLE JSON -

    {
      "count": 30,
      "recipes": [
        {
          "publisher": "Closet Cooking",
          "f2f_url": "http:\/\/food2fork.com\/view\/35382",
          "title": "Jalapeno Popper Grilled Cheese Sandwich",
          "source_url": "http:\/\/www.closetcooking.com\/2011\/04\/jalapeno-popper-grilled-cheese-sandwich.html",
          "recipe_id": "35382",
          "image_url": "http:\/\/static.food2fork.com\/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg",
          "social_rank": 100,
          "publisher_url": "http:\/\/closetcooking.com"
        },
        {
          "publisher": "The Pioneer Woman",
          "f2f_url": "http:\/\/food2fork.com\/view\/47024",
          "title": "Perfect Iced Coffee",
          "source_url": "http:\/\/thepioneerwoman.com\/cooking\/2011\/06\/perfect-iced-coffee\/",
          "recipe_id": "47024",
          "image_url": "http:\/\/static.food2fork.com\/icedcoffee5766.jpg",
          "social_rank": 100,
          "publisher_url": "http:\/\/thepioneerwoman.com"
        },
       ]
    }
    

    I tried this -

    AndroidNetworking.get(Constants.RECIPE_DUMMY_ENDPOINT)
                   .setPriority(Priority.HIGH)
                   .build()
                   .getAsObjectList(Recipe.class, new ParsedRequestListener<List<Recipe>>() {
                       @Override
                       public void onResponse(List<Recipe> response) {
                           Log.i(TAG, "onResponse: "+response.size());
                           Log.i(TAG, "onResponse: "+response.get(0).toString());
                       }
    
                       @Override
                       public void onError(ANError anError) {
                           Log.e(TAG, "onError: "+anError.getErrorDetail() );
    
                       }
                   });
    

    It gives parsing error - E/MainActivity: onError: parseError The Recipe class contains all the getters,setters and parameterised constructor for each of the JSON objects inside the JSON array "responses". Where am I going wrong?

    opened by knightcube 14
  • Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

    Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

    I get this error when sending a get request

    this is my code:

    ** build.gradle ** `apply plugin: 'com.android.application'

    android { compileSdkVersion 25 buildToolsVersion "26.0.2" defaultConfig { applicationId "ir.supersoft.androidfastnetworking" minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }

    dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support.constraint:constraint-layout:1.0.2' compile 'com.amitshekhar.android:android-networking:1.0.0' compile 'com.library.tangxiaolv:telegramgallery:1.0.3' } `

    User.java `public class User {

    public int id; public String first_name; public String last_name; public int age; } `

    MainActivity.java AndroidNetworking.initialize(getApplicationContext());

    `AndroidNetworking.get("http://sekeh.gigfa.com/getUsers.php") .setTag("test") .setPriority(Priority.LOW) .build() .getAsOkHttpResponseAndObjectList(User.class, new OkHttpResponseAndParsedRequestListener<List>() { @Override public void onResponse(Response okHttpResponse, List users) { // do anything with response Log.d("amirhosein", "userList size : " + users.size()); for (User user : users) { Log.d("amirhosein", "id : " + user.id); Log.d("amirhosein", "firstname : " + user.first_name); Log.d("amirhosein", "lastname : " + user.last_name); Log.d("amirhosein", "age : " + user.age); } }

            @Override
            public void onError(ANError anError) {
              Log.e("amirhosein", "error: " + anError.getLocalizedMessage());
            }
          });
    

    `

    i test that in localhost(xampp) but it`s worked!

    keep in mind that my androidnetworking version is 1.0.0 because 1.0.1 need to appcompatv7:27.0.2

    opened by amirhoseinpourali 14
  •  Exception com.androidnetworking.error.ANError: com.androidnetworking.error.ANError: java.net.SocketTimeoutException

    Exception com.androidnetworking.error.ANError: com.androidnetworking.error.ANError: java.net.SocketTimeoutException

    Hi, I know maybe will be slowly my internet speed, I know maybe requests will be timeout, but why crash?

    library not called to onError callback, crash when doing request: Caused by java.net.SocketTimeoutException: java.net.PlainSocketImpl.read (PlainSocketImpl.java:488) java.net.PlainSocketImpl.access$000 (PlainSocketImpl.java:37) java.net.PlainSocketImpl$PlainSocketInputStream.read (PlainSocketImpl.java:237) okio.Okio$2.read (Okio.java:138) okio.AsyncTimeout$2.read (AsyncTimeout.java:236) okio.RealBufferedSource.indexOf (RealBufferedSource.java:325) okio.RealBufferedSource.indexOf (RealBufferedSource.java:314) okio.RealBufferedSource.readUtf8LineStrict (RealBufferedSource.java:210) okhttp3.internal.http1.Http1Codec.readResponseHeaders (Http1Codec.java:189) okhttp3.internal.http.CallServerInterceptor.intercept (CallServerInterceptor.java:67) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92) okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.java:45) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67) okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:93) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67) okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:93) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92) okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:120) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67) com.androidnetworking.interceptors.HttpLoggingInterceptor.intercept (HttpLoggingInterceptor.java:221) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67) okhttp3.RealCall.getResponseWithInterceptorChain (RealCall.java:179) okhttp3.RealCall.execute (RealCall.java:63) com.androidnetworking.internal.InternalNetworking.performSimpleRequest (InternalNetworking.java:112) com.androidnetworking.internal.InternalRunnable.executeSimpleRequest (InternalRunnable.java:68) com.androidnetworking.internal.InternalRunnable.run (InternalRunnable.java:54) java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:422) java.util.concurrent.FutureTask.run (FutureTask.java:237) java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112) java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:587) com.androidnetworking.core.PriorityThreadFactory$1.run (PriorityThreadFactory.java:47) java.lang.Thread.run (Thread.java:818)

    Anybody know how to fix it?

    opened by sm-tester 13
  • why add header is no action

    why add header is no action

    like this public static void postStringJson(String url, HashMap<String,String> params,StringRequestListener listener){ AndroidNetworking.post(url).addHeaders(getRequestHeader()).addBodyParameter(params).build().getAsString(listener); }

    public static HashMap<String,String> getRequestHeader(){
        HashMap<String,String> headParams = new HashMap<>();
        headParams.put("Content-Type", "application/json");
        String token = SharedPreferenceUtil.getInstance(AppApplication.getInstance()).getString(SharedPreferenceUtil.TOKEN);
        if(!StringUtil.isEmpty(token)){
            headParams.put("Authorization","token "+token);
        }
        headParams.put("client","android");
    
        return headParams;
    }
    
    opened by LOWANGA 12
  • Request always fails when the url is an IP address.

    Request always fails when the url is an IP address.

    When I make a request and the url is an IP address, the request always fails as if the server doesn't exist. I've tried making the exact same request using different clients and it works. Please help.

    Refer to the code below

    This works.

    //works
    AndroidNetworking.get("http://example.com/")
                    .addHeaders(AUTHORIZATION, TOKEN_ + token)
                    .setPriority(Priority.MEDIUM)
                    .build()
                    .getAsJSONObject(object : JSONObjectRequestListener {
                        override fun onResponse(response: JSONObject) {
                            recentPriceMessage.value = Gson().fromJson(response.toString(), RecentPriceModel::class.java)
                        }
                        override fun onError(anError: ANError) {
                            Log.e("error", anError.errorBody)
                        }
                    })
    
    

    This doesn't work.

    //fails
    AndroidNetworking.get("http://192.0.0.1/endpoint/")
                    .addHeaders(AUTHORIZATION, TOKEN_ + token)
                    .setPriority(Priority.MEDIUM)
                    .build()
                    .getAsJSONObject(object : JSONObjectRequestListener {
                        override fun onResponse(response: JSONObject) {
                            recentPriceMessage.value = Gson().fromJson(response.toString(), RecentPriceModel::class.java)
                        }
                        override fun onError(anError: ANError) {
                            Log.e("error", anError.errorBody)
                        }
                    })
    
    opened by charlesganza 11
  • how to get return value onResponse or onError ?

    how to get return value onResponse or onError ?

    i must admit im new in java... sorry for including this in issues hope it would help others inexperience people who using this library. how to get return value in void onResponse Method ?

    i have already using OptimusHttp that using Volley in their base connection library. as i know on that library it would support to return any value from OnSuccess method by using Interface Callback.

    can u help me how to accomplish it using this library ?

    
     api.get(this.host+"login")
                    .setPriority(Priority.HIGH)
                    .build()
                        .getAsJSONObject(new JSONObjectRequestListener() {
                            @Override
                            public void onResponse(JSONObject response) {
    
                                try {
                                         // need to return value here such as 
                                       **return response;  --> error**                      
                               } catch (Exception e) {
                                    System.out.println(e.toString());
                                }
                            }
    
                            @Override
                            public void onError(ANError anError) {
                                    messageToast("error");
                            }
    
                    });
    
    

    thanks u

    question 
    opened by navotera 11
  • Error building project

    Error building project

    Duplicate class android.support.v4.app.INotificationSideChannel found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.app.INotificationSideChannel$Stub found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.app.INotificationSideChannel$Stub$Proxy found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.os.IResultReceiver found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.os.IResultReceiver$Stub found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.os.IResultReceiver$Stub$Proxy found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.os.ResultReceiver found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.os.ResultReceiver$1 found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.os.ResultReceiver$MyResultReceiver found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1) Duplicate class android.support.v4.os.ResultReceiver$MyRunnable found in modules core-1.8.0-runtime (androidx.core:core:1.8.0) and support-compat-27.1.1-runtime (com.android.support:support-compat:27.1.1)

    opened by srjmca 0
  • Failed to resolve:

    Failed to resolve:

    Hello, the module cannot be downloaded Mac operating system error:Failed to resolve: com.amitshekhar.android:android-networking:1.0.2

    https://s6.uupload.ir/files/screen_shot_2022-10-30_at_4.11.39_pm_ec7f.png

    Screen Shot 2022-10-30 at 4 11 39 PM
    opened by okdude24 8
  • Could not find com.amitshekhar.android:android-networking:1.0.2.

    Could not find com.amitshekhar.android:android-networking:1.0.2.

    I have used android studio Chipmunk

    My settings.gradle file

    pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() maven { url "https://jitpack.io" } } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url "https://jitpack.io" } } }

    opened by saurabh-proaxiom 4
  • AndroidNetworking.initialize(getApplicationContext()); Not working

    AndroidNetworking.initialize(getApplicationContext()); Not working

    After adding (implementation 'com.amitshekhar.android:android-networking:1.0.2') this to my build.gradle. Error : Cannot resolve symbol 'AndroidNetworking. Please solve the issue.

    opened by raktim1998 9
Releases(v1.0.2)
  • v1.0.2(Jul 10, 2018)

    • New: Add support for multiple file upload with same key
    • New: Add support for multi contentType in multipart
    • Bump OkHttp Version to 3.10.0
    • Bump other dependencies
    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Dec 20, 2017)

    • New: Add support for Single, Completable, Flowable, Maybe Observable
    • New: Add support for OPTIONS request
    • Bump OkHttp Version to 3.9.1
    • Bump other dependencies
    • New: Add support for specifying request method dynamically
    • New: Add API to check isRequestRunning
    • Fix: Add more than one values for one key in header and query
    • Merge pull requests
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Mar 19, 2017)

    • Fix Progress Bug for large files download
    • Merge pull requests
    • Add new API
    • Bump OkHttpVersion
    • Add config options for BitmapDecode
    • Add Consumer Proguard
    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(Feb 1, 2017)

    RxJava2 Support link Add Java Object directly in any request link Java Object is supported for query parameter, headers also Update OkHttp to 3.5.0 Allow all Map implementations Add better logging of request Get parsed error body link Merged pull requests

    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Nov 7, 2016)

  • v0.2.0(Sep 15, 2016)

    • Jackson Parser Support

      compile 'com.amitshekhar.android:jackson-android-networking:0.2.0'
      // Then set the JacksonParserFactory like below
      AndroidNetworking.setParserFactory(new JacksonParserFactory());
      
    • Making Synchronous Request - Check Here

    • setContentType("application/json; charset=utf-8") in POST and Multipart request.

    • Getting OkHttpResponse in Response to access headers - Check Here

    • Bug fixes : As always we are squashing bugs.

    • Few other features which are request by the fans of Fast Android Networking.

    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jul 31, 2016)

    • RxJava Support For Fast-Android-Networking
    • Now RxJava can be used with Fast-Android-Networking
    • Operators like flatMap, filter, map, zip, etc can be used easily with Fast-Android-Networking.
    • Chaining of Requests can be done.
    • Requests can be bind with Activity-Lifecycle.
    • Java Object Parsing Support
    Source code(tar.gz)
    Source code(zip)
  • v0.0.1(Jun 3, 2016)

Owner
AMIT SHEKHAR
Always Learning and Sharing | Co-Founder @ CuriousJr, MindOrks, AfterAcademy
AMIT SHEKHAR
The easiest HTTP networking library for Kotlin/Android

Fuel The easiest HTTP networking library for Kotlin/Android. You are looking at the documentation for 2.x.y.. If you are looking for the documentation

Kittinun Vantasin 4.3k Jan 8, 2023
Volley is an HTTP library that makes networking for Android apps easier and, most importantly, faster.

Volley Volley is an HTTP library that makes networking for Android apps easier and, most importantly, faster. For more information about Volley and ho

Google 3.3k Jan 1, 2023
IceNet - Fast, Simple and Easy Networking for Android

IceNet FAST, SIMPLE, EASY This library is an Android networking wrapper consisting of a combination of Volley, OkHttp and Gson. For more information s

Anton Nurdin Tuhadiansyah 61 Jun 24, 2022
Android Easy Http - Simplest android http request library.

Android Easy Http Library 繁體中文文檔 About Android Easy Http Library Made on OkHttp. Easy to do http request, just make request and listen for the respons

null 13 Sep 30, 2022
LiteHttp is a simple, intelligent and flexible HTTP framework for Android. With LiteHttp you can make HTTP request with only one line of code! It could convert a java model to the parameter and rander the response JSON as a java model intelligently.

Android network framework: LiteHttp Tags : litehttp2.x-tutorials Website : http://litesuits.com QQgroup : 42960650 , 47357508 Android网络通信为啥子选 lite-htt

马天宇 829 Dec 29, 2022
:satellite: [Android Library] Simplified async networking in android

Android library that simplifies networking in android via an async http client. Also featured in [Awesome Android Newsletter #Issue 15 ] Built with ❤︎

Nishant Srivastava 36 May 14, 2022
Flower - Super cool Android library to manage networking and database caching with ease

Flower Super cool Android library to manage networking and database caching with ease. It allows developers to use remote resources on-the-fly OR Comb

Rajesh Hadiya 192 Dec 26, 2022
Kotlin-echo-client - Echo client using Kotlin with Ktor networking library

Overview This repository contains an echo server implemented with Kotlin and kto

Elliot Barlas 2 Sep 1, 2022
Android Asynchronous Networking and Image Loading

Android Asynchronous Networking and Image Loading Download Maven Git Features Kotlin coroutine/suspend support Asynchronously download: Images into Im

Koushik Dutta 6.3k Dec 27, 2022
Latihan Networking dengan Retrofit

Latihan-Background-Process-dan-Networking-9 Latihan Networking dengan Retrofit Pada materi kali ini Anda akan belajar menggunakan Retrofit untuk menam

Ubean 0 Nov 25, 2021
Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

AndroidAsync AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request li

Koushik Dutta 7.3k Jan 2, 2023
Asynchronous Http and WebSocket Client library for Java

Async Http Client Follow @AsyncHttpClient on Twitter. The AsyncHttpClient (AHC) library allows Java applications to easily execute HTTP requests and a

AsyncHttpClient 6k Jan 8, 2023
HttpMocker is a simple HTTP mocking library written in Kotlin to quickly and easily handle offline modes in your apps

HttpMocker HttpMocker is a very lightweight Kotlin library that allows to mock HTTP calls relying on either OkHttp or the Ktor client libraries. It ca

David Blanc 174 Nov 28, 2022
Kotlin HTTP requests library. Similar to Python requests.

khttp khttp is a simple library for HTTP requests in Kotlin. It functions similarly to Python's requests module. import khttp.get fun main(args: Arra

Anna Clemens 466 Dec 20, 2022
Java HTTP Request Library

Http Request A simple convenience library for using a HttpURLConnection to make requests and access the response. This library is available under the

Kevin Sawicki 3.3k Jan 6, 2023
Unirest in Java: Simplified, lightweight HTTP client library.

Unirest for Java Install With Maven: <!-- Pull in as a traditional dependency --> <dependency> <groupId>com.konghq</groupId> <artifactId>unire

Kong 2.4k Jan 5, 2023
super simple library to manage http requests.

HttpAgent super simple library to manage http requests. Gradle dependencies { implementation 'com.studioidan.httpagent:httpagent:1.0.16@aar' } No

idan ben shimon 32 Oct 24, 2021
Unirest in Java: Simplified, lightweight HTTP client library.

Unirest for Java Install With Maven: <!-- Pull in as a traditional dependency --> <dependency> <groupId>com.konghq</groupId> <artifactId>unire

Kong 2.4k Dec 24, 2022