NetRequest


Source link: https://github.com/thunder413/NetRequest

NetRequest

This lightweight library makes it easy to use HTTP requests. Although the purpose is to make the use of Json data easy, it also allows to retrieve the server response using other formats, XML and TEXT.

This library is available under the MIT License.

Usage

The NetRequet library is available from JitPack.

First add JitPack dependency line in your project build.gradle file:

allprojects {
  repositories {

...
maven {
 url 'https://jitpack.io' 
}
  
}
 
}

And then simply add the following line to the dependencies section of your app module build.gradle file:

compile 'com.github.thunder413:NetRequest:1.4'

Javadocs are available here.

FAQ

What is the Purpose?

I'm sure that every android developer notice that most of the time when it come to make HTTP request it's about pulling structured data from the server such as JSON or XML , of course there are other libraries that handle quiet well the same kind of data but they are also shipped with other bunch of parsers that you may not need. In the other hand it's a matter of taste regarding the callbacks and how the request is built which drives me to develop this library

The Library is built on top of kevinsawicki http-request library which is a great library for using an HttpURLConnection and by the way if you are interested in handling Http request by yourself, I highly recommend you to give it a try

How are requests managed?

The NetRequest library is queue based which mean that requests are stored in a pool and then executed, but you can control the execution mode while in the most case you will need the requests to be run in parallel (which is the default behavior) you can also turn that off and make the pool executor to run requests in sequence using setParallelRequestEnabled(boolean state).

How To ?

Initialize manager

NetRequest has a manager but it auto-manage itself and using it is optional however it is useful in some cases, especially when you have repeating treatment, like always have to send a user_id every time you perform an http request. It also allow you to control the library behavior like printing debug in development mode or enabling/disabling parallel execution .

I recommend you to do it once in onCreate of your application class but you can use it anywhere you would like.

NetRequestManager.getInstance()
.setDebug(true) // Enable debug false default
.setParallelRequestEnabled(true) // Default
.addParamter("user_id",1) // send user_id each time a request is made
.addParameter("username","john") // same as user_id
.addParamters(Map<String,Object> map) // or add parameters as map
;

Build and execute a request

NetRequest netRequest = new NetRequest(context);
 netRequest.load("http://google.com");

You can also use setRequestUri to set your url

NetRequest netRequest = new NetRequest(context);
 netRequest.setRequestUri("http://google.com");
 netRequest.load();

Perform a GET/POST Request

The default method is GET

netRequest.setRequestMethod(RequestMethod.GET|RequestMethod.POST);
 netRequest.load("http://google.com");

Adding query parameters

netRequest.addParameter("id",1);
 netRequest.addParameter("username","john");
 netRequest.addParameter("password","********");
 netRequest.load("http://google.com");

Using map as query parameters

// Build your map Map<String,Object> map = new HashMap<>();

map.put("id",1);

map.put("username","john");

map.put("password","*****");
 netRequest.addParameterSet(map);
 netRequest.load("http://google.com");

What kind of data are you expecting ?

The default expected data is RequestDataType.JSON but you can also set it up using setRequestDataType

netRequest.setRequestDataType(RequestDataType.XML);
 netRequest.load("http://google.com/xml");

Get the request ressult

netRequest.setOnResponseListener(new OnNetResponse() {

@Override
public void onNetResponseCompleted(NetResponse response) {

  Log.d("TAG",response.toString());

}

@Override
public void onNetResponseError(NetError error) {

  Log.d("TAG",error.toString());

}
 
}
);
 netRequest.load("http://google.com");

setOnResponseListener expect an interface so you can make your activity or fragment implement OnNetResponseListener class

Handle response

...
@Override
public void onNetResponseCompleted(NetResponse response) {

 // Get response
  Log.d("TAG",response.toString());

  // If you are expecting json data just use
  JsonObject data = response.toJson();

  // If you are exepecting xml data just use
  Document xml = response.toXML();

  // You can also rely on the dataType from response
  RequestDataType dataType = response.getRequestDataType();

  if(dataType.equals(RequestDataType.JSON)) {

}
 else if(dataType.equals(RequestDataType.XML)){

}

}
 ...

Handle errors

...
@Override
public void onNetResponseError(NetError error) {

 Log.d("TAG",error.toString());

  // Handle error
  switch (error.getStatus()) {

case CONNECTION_ERROR: // No internet connection detected

break;

case PARSE_ERROR: // Fail to parse data into request data type

break;

case ERROR: // Error

break;

case INVALID_URI_ERROR: // when no uri is supplied or null

break;

case NOT_FOUND: // HttpStatus 404

break;

case BAD_GATEWAY: // HttpStatus 502

break;

case SERVER_ERROR: // Any other HTTPStatus error 

break;

 case REQUEST_ERROR: // Internal module error

break;

case CANCELED: // Request cancelled

break;

}

}
 ...

Cancel a request

You can cancel a request at any time using cancel on your netRequest instance

// Just call cancel on your netRequest instance NetRequet netRequest = new NetRequest(context);
 netRequest.load("http://google.com");
 // Later netRequest.cancel()

Request TAG

NetRequest allow you to use tags, this is usefull when in one activity or fragment you have to make multiple request you can re-use the OnResponseListener

... // Tag can be any data type you would like (Integer,String,Object ....) netRequest.setTag(tag);
 netRequest.setOnResponseListener(new OnNetResponse() {

  @Override
  public void onNetResponseCompleted(NetResponse response) {

  Log.d("TAG",response.toString());

// Deal with tag
  Object tag = response.getTag();

}

@Override
  public void onNetResponseError(NetError error) {
  

 Log.d("TAG",error.toString());

  // Deal with tag
  Object tag = error.getTag();

}
 
}
);
 netRequest.load("http://google.com");

Author

License

This project is licensed under the MIT License

Acknowledgments

Resources

An android lib for enhancing BottomNavigationView.

The library came out as an effort to reduce the boilerplate required for getting runtime permissions for Android devices running OS 6.0 and above.

The developer can now focus on handling the granted and denied state of the permission rather than dealing with the permission flow and dialogues.

A custom reusable circular slider control for Android application.

MP3 audio recording component.

This project helps for who faced problem with WebView inside NestedScrollView.

LabelLayout is a powerful layout to display label on top of another view

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes