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.

Overview

Android network framework: LiteHttp

Tags : litehttp2.x-tutorials


Website : http://litesuits.com

QQgroup : 42960650 , 47357508

Android网络通信为啥子选 lite-http ?

lite-http 初步使用 和 快速上手


1. What‘s lite-http ?

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.

2. Why choose lite-http ?

Simple, powerful, make HTTP request with only one line of code:

User user = liteHttp.get (url, User.class);

asynchronous download a file(execute on sub-thread,listen on ui-thread):

liteHttp.executeAsync(new FileRequest(url,path).setHttpListener(
	new HttpListener<File>(true, true, true) {
	
        @Override
        public void onLoading(AbstractRequest<File> request, long total, long len) {
            // loading notification
        }

        @Override
        public void onSuccess(File file, Response<File> response) {
            // successfully download 
        }
		
	})
);

configure an asynchronous login request by annotation:

String loginUrl = "http://litesuits.com/mockdata/user_get";

// 1. URL        : loginUrl
// 2. Parameter  : name=value&password= value
// 3. Response   : User
@HttpUri(loginUrl) 
class LoginParam extends HttpRichParamModel<User> {
    private String name;
    private String password;

    public LoginParam(String name, String password) {
        this.name = name;
        this.password = password;
    }
}
liteHttp.executeAsync(new LoginParam("lucy", "123456"));

will be built as http://xxx?name=lucy&password=123456

more details, you can see lite-http introduction: LiteHttp Introduction: Why should developers choose LiteHttp ?

3. What are the fetures ?

  • Lightweight: tiny size overhead to your app. About 99kb for core jar. .

  • One-Thread-Based: all methods work on the same thread as the request was created.

  • Full support: GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS, PATCH.

  • Automatic: one line of code auto-complete translation between Model and Parameter, Json and Model.

  • Configurable: more flexible configuration options, up to 23+ items.

  • Polymorphic: more intuitive API, input and output is more clear.  

  • Strong Concurrency: concurrent scheduler that comes with a strong, effective control of scheduling and queue control strategies.

  • Annotation Usage: convention over configuration. Parameters, Response, URL, Method, ID, TAG, etc. Can be configured.

  • Easy expansion: extend the abstract class DataParser to parse inputstream(network) to which you want..

  • Alternatively: interface-based, easy to replace the network connection implementations and Json serialization library.

  • Multilayer cache: hit Memory is more efficient! Multiple cache mode. Support for setting cache expire time.

  • Callback Flexible: callback can be on current or UI thread. listen the beginning, ending, success or failure, uploading, downloading, etc.

  • File Upload: support for single, multiple, large file uploads.

  • Downloads: support files, Bimtap download and progress notifications.

  • Network Disabled: disable one of a variety of network environments, such as specifying disabling 2G, 3G.

  • Statistics: time cost statistics and traffic statistics.

  • Exception system: a unified, concise, clear exception is thrown into three categories: client, network, server, and abnormalities can be accurately subdivided.

  • GZIP compression: automatic GZIP compression.

  • Automatic Retry: combined probe exception type and current network conditions, intelligent retry strategies.

  • Automatic redirection: based on the retry 30X state, and can set the maximum number of times to prevent excessive jump.

4. Overall architecture of lite-http

Lite-http Chart

About App architecture, see my other article: [How to take high-quality Android project framework, the framework of the structure described in detail? ] 7

5. tutorials and analysis (◕‸◕)

Good ◝‿◜, huh:

 [1. Initialization and preliminary usage] 8

 [2. Simplified requests and non-safe method of use] 9

 [3. Automatic model conversion] 10

 [4. Custom DataParser and Json serialization library Replace] 11

 [5. Files, bitmap upload and download] 12

 [6. Disable network and traffic statistics] 13

 [7. Retries and redirect] 14

 [8. Exceptions handling and cancellation request] 15

 [9. Multiple data transmission via POST(PUT)] 16

 [10. Asynchronous concurrency and scheduling strategy] 17

 [11. Global configuration and parameter settings Detailed] 18

 [12. Annotation-Based request] 19

 [13. Multilayer cache mechanism and usage] 20

 [14. Detailed of callback listener] 21

 [15. SmartExecutor: concurrent scheduler] 22

LiteHttp: Android网络通信框架

中文版 换个语种,再来一次

标签: litehttp2.x版本系列教程


官网: http://litesuits.com

QQ群: 大群 47357508二群 42960650

Android网络框架为什么可以选用lite-http?

lite-http 初步使用 和 快速起步上手

本系列文章面向android开发者,展示开源网络通信框架LiteHttp的主要用法,并讲解其关键功能的运作原理,同时传达了一些框架作者在日常开发中的一些最佳实践和经验。


LiteHttp之开篇简介和大纲目录

1. lite-http是什么? (・̆⍛・̆)

LiteHttp是一款简单、智能、灵活的HTTP框架库,它在请求和响应层面做到了全自动构建和解析,主要用于Android快速开发。

2. 为什么选lite-http? (•́ ₃ •̀)

简单、强大,线程无关,一行代码搞定API请求和数据转化:

User user = liteHttp.get(url, User.class);

当然也可以开启线程异步下载文件:

liteHttp.executeAsync(new FileRequest(url,path).setHttpListener(
	new HttpListener<File>(true, true, true) {
	
        @Override
        public void onLoading(AbstractRequest<File> request, long total, long len) {
            // loading notification
        }

        @Override
        public void onSuccess(File file, Response<File> response) {
            // successfully download 
        }
		
	})
);

通过注解约定完成异步请求:

@HttpUri(loginUrl) 
class LoginParam extends HttpRichParamModel<User> {
    private String name;
    private String password;

    public LoginParam(String name, String password) {
        this.name = name;
        this.password = password;
    }
}
liteHttp.executeAsync(new LoginParam("lucy", "123456"));

将构建类似下面请求:http://xxx?name=lucy&password=123456

案例详情可见我另一篇lite-http引言文章:LiteHttp 引言:开发者为什么要选LiteHttp??

3. lite-http有什么特点? (´ڡ`)

  • 轻量级:微小的内存开销与Jar包体积,99K左右。

  • 单线程:请求本身具有线程无关特性,基于当前线程高效率运作。

  • 全支持:GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS, PATCH。

  • 全自动:一行代码自动完成Model与Parameter、Json与Model。

  • 可配置:更多更灵活的配置选择项,多达 23+ 项。

  • 多态化:更加直观的API,输入和输出更加明确。

  • 强并发:自带强大的并发调度器,有效控制任务调度与队列控制策略。

  • 注解化:通过注解约定参数,URL、Method、ID、TAG等都可约定。

  • 易拓展:自定义DataParser将网络数据流转化为你想要的数据类型。

  • 可替换:基于接口,轻松替换网络连接实现方式和Json序列化库。

  • 多层缓存:内存命中更高效!多种缓存模式,支持设置缓存有效期。

  • 回调灵活:可选择当前或UI线程执行回调,开始结束、成败、上传、下载进度等都可监听。

  • 文件上传:支持单个、多个大文件上传。

  • 文件下载:支持文件、Bimtap下载及其进度通知。

  • 网络禁用:快速禁用一种、多种网络环境,比如指定禁用 2G,3G 。

  • 数据统计:链接、读取时长统计,以及流量统计。

  • 异常体系:统一、简明、清晰地抛出三类异常:客户端、网络、服务器,且异常都可精确细分。

  • GZIP压缩:Request, Response 自动 GZIP 压缩节省流量。

  • 自动重试:结合探测异常类型和当前网络状况,智能执行重试策略。

  • 自动重定向:基于 30X 状态的重试,且可设置最大次数防止过度跳转。

4. lite-http的整体架构是怎样的呀? (´ڡ`)

lite-http架构图

关于App架构,请看我另一篇文章分享: 怎样搭高质量的Android项目框架,框架的结构具体描述?

5. 老湿,来点教学和分析带我飞呗? (◕‸◕)

好的 ◝‿◜ ,下面直接给你看,疗效好记得联系我,呵呵哒:

1. 初始化和初步使用

2. 简化请求和非安全方法的使用

3. 自动对象转化

4. 自定义DataParser和Json序列化库的替换

5. 文件、位图的上传和下载

6. 禁用网络和流量、时间统计

7. 重试和重定向

8. 处理异常和取消请求

9. POST方式的多种类型数据传输

10. lite-http异步并发与调度策略

11. 全局配置与参数设置详解

12. 通过注解完成API请求

13. 多层缓存机制及用法

14. 回调监听器详解

15. 并发调度控制器详解

Comments
  • 通过HttpParamModel接口无法传参?

    通过HttpParamModel接口无法传参?

    参考: https://zybuluo.com/liter/note/187568 (1. 简单参数 HttpParamModel) 版本: lite-http-2.1.5.jar 继承HttpRichParamModel方式调试正常... 但是通过以下方式请求时, 发现日志中没有输出请求参数!!! LiteHttp liteHttp = LiteHttp.newApacheHttpClient(null); liteHttp.getConfig().setDebugged(true); liteHttp.executeAsync(new JsonRequest(new Goods(1, 0), ApiModel.class)); //LOG I/LiteHttp: lite http request: http://sgarss.com:8080/FruitLover/fruitlover/api/goods? , tag: null , method: Get , cache mode: null , thread ID: 7536 , thread name: lite-1 //param参数page和type没有输出...服务端也没有收到请求参数

    /////////////////////////附加代码1 @HttpUri("http://sgarss.com:8080/FruitLover/fruitlover/api/goods") public static class Goods implements HttpParamModel { public Integer page; public Integer type; public Goods(Integer page, Integer type) { this.page = page; this.type = type; } }

    //////////////////////附加代码2 public final class ApiModel { public Integer stateCode; public String message; public String result; public boolean isSuccess() { return stateCode == 200; } }

    opened by bf3400 6
  • android studio 提示HttpCacheExpire.class重复

    android studio 提示HttpCacheExpire.class重复

    Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.

    com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/litesuits/http/annotation/HttpCacheExpire.class

    这个要怎么处理啊?弄的头都大了

    opened by lyx32 2
  • Cookie refected

    Cookie refected

    Cookie rejected: "BasicClientCookie[version=0,name=_da_ntes_uid,domain=xxxx,path=/,expiry=Thu Jan 05 09:44:27 GMT+08:00 2017]".

    Server Reject Client Exception (服务器拒绝或无法提供服务), code: 400, Bad Request

    请问cookie如何设置?

    opened by shuleihen 2
  • 请求失败

    请求失败

    我在请求这个连接时失败 String url = "http://wap.cmread.com/r/400270618/400644484/index.htm?vt=9&cm=M2040002"; getJson2: LiteHttpClient client = LiteHttpClient.newApacheHttpClient(this,"Mozilla/5.0"); Response res = client.execute(new Request(url)); return res.getString(); 但是使用org.apache的httpclient就能成功: HttpGet get = new HttpGet(url); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); log("status = " + response.getStatusLine()); log("content " + response.getEntity().getContentLength()); InputStream in = response.getEntity().getContent(); return getStringFromInputStream(in); 这个链接多次重定向, 错误是 02-05 10:45:07.936: W/System.err(18855): 服务器拒绝或无法提供服务, http status code 400, Bad Request, 请求错误(请检查语义和参数) 02-05 10:45:07.936: W/System.err(18855): at com.litesuits.http.impl.apache.ApacheHttpClient.readDataWithRetries(ApacheHttpClient.java:483) 02-05 10:45:07.941: W/System.err(18855): at com.litesuits.http.impl.apache.ApacheHttpClient.readDataWithRetries(ApacheHttpClient.java:473) 02-05 10:45:07.941: W/System.err(18855): at com.litesuits.http.impl.apache.ApacheHttpClient.readDataWithRetries(ApacheHttpClient.java:473) 02-05 10:45:07.941: W/System.err(18855): at com.litesuits.http.impl.apache.ApacheHttpClient.execute(ApacheHttpClient.java:216) 02-05 10:45:07.941: W/System.err(18855): at com.example.test.MainActivity.getJson2(MainActivity.java:117) 02-05 10:45:07.941: W/System.err(18855): at com.example.test.MainActivity$1.run(MainActivity.java:69)

    opened by jinguoliang 2
  • 版本3.1.3.6 返回404

    版本3.1.3.6 返回404

    我用3.1.3.6请求一个接口。 返回404.但是我用PC浏览器,手机浏览器,HttpURLConnection都可以正常请求。 就是用litehttp请求返回404. 接口如下: http://www.hqls.com.cn/Hqapkservices?zGPwn54hK4KvD9q7++KIqwKQi6AkdjB3/jLXDXa1al/YW7RMPK1jD93GLHdM5IUYHeOM2/rzhYLxjt6Wuo+CIxSTYeRIZjqUSxOETI3juiTW+2edZeIPx1t3fPlM3E3y

    opened by lyx32 0
  • 你们用这个框架的时候有没有报ConcurrentModificationException?

    你们用这个框架的时候有没有报ConcurrentModificationException?

    java.util.ConcurrentModificationException at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(LinkedHashMap.java:346) at java.util.LinkedHashMap$EntryIterator.next(LinkedHashMap.java:375) at java.util.LinkedHashMap$EntryIterator.next(LinkedHashMap.java:375) at com.litesuits.http.request.AbstractRequest.reqToString(AbstractRequest.java) at com.litesuits.http.request.AbstractRequest.toString(AbstractRequest.java) at java.lang.StringBuilder.append(StringBuilder.java:202)

    感觉是reqToString中没有做线程安全处理导致,现在这个bug友盟每天都报,是我这个项目里最大的bug。

    opened by feiyuu 1
  • 这个链接请求,中文乱码!

    这个链接请求,中文乱码!

    这是地址: http://www.sh-link.com/MagicDisc_bin/HelperDoc/helperhtml.txt

    我这样请求是正常的中文: URL url = new URL(uri); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), "GBK"));

    opened by Apples0609 0
Owner
马天宇
welcome to http://litesuits.com
马天宇
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
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
MVVM with simple HTTP Request Example

Minimum MVVM Koin (Kotlin Dependency Injection) Coroutines View Model Lifecycle News API Retrofit Rx Java Rx Android OkHttp Client Result ScreenShot 1

Faisal Amir 6 Dec 1, 2022
Allows recording and playback http request/responses for testing purposes.

Allows recording and playback http request/responses for testing purposes.

Cristian Gómez 4 Aug 4, 2022
Allows recording and playback http request/responses for testing purposes.

Test Record Interceptor est Record Interceptor allows to record responses from http request to be replayed at tests. How it works Use regular http cal

Cristian Gómez 4 Aug 4, 2022
A small Android project to practice executing network requests and parsing the network response

InspirationalQuotesExercise A small Android project to practice executing network requests and parsing the network response This app uses the ZenQuote

Caren 0 Oct 13, 2021
TART: Tracing Action Response Times

Square Tart Tracing Action Response Times! This library is not stable for usage beyond Square, the APIs and internals might change anytime. Tart... ?

Square 246 Nov 24, 2022
This application provide purchase request service for Membership Console.

Purchase Request 概要 本プロジェクトはMembership Consoleの購入申請機能を提供します。 開発 開発環境 Java OpenJDK 17 Kotlin 1.7.10 Ktor 2.1.2 PostgreSQL 13 docker-compose ビルド方法 ビルドに成

Membership Console 2 Nov 17, 2022
Handle various HTTP status code by safe api call with Result sealed class

retrofit2-safe-api-call Handle various HTTP status code by safe api call with Result sealed class Library Retrofit2 OkHttp3 Gson Coroutine DI : Koin V

Jaesung Lee 2 May 16, 2022
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
Mock your datas for Okhttp and Retrofit in json format in just a few moves

okhttp-json-mock This simple library helps you mock your data for using with okhttp+retrofit in json format in just a few moves. it forwards the reque

Mad Mirrajabi 240 Nov 25, 2022
Display list of item from local Json and download, view after downloading

Download App Features: ● Display fake responses for the list of videos and books ● choose one or multiple files to download, ● show the download perce

Mahmoud Othman 1 Dec 25, 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 Jan 5, 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 Dec 24, 2022
Monitoring water tanker level using NodeMCU ESP8266 and HC-SR04P Ultrasonic Sensor and broadcasting it using a simple HTTP server inside NodeMCU ESP8266 and show data in an Android App

WaterLevel Preface This project aims to finding a tanker water level using NodeMCU with ESP8266 core and HC-SR04P Ultrasonic sensor and broadcasting i

YaMiN 12 Dec 20, 2022
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
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
Compact and easy to use, 'all-in-one' android network solution

Deprecated Unfortunately due to many reasons including maintenance cost, this library is deprecated. I recommend to use Retrofit/OkHttp instead. Curre

Orhan Obut 585 Dec 30, 2022
Pluto is a on-device debugger for Android applications, which helps in inspection of HTTP requests/responses, capture Crashes and ANRs and manipulating application data on-the-go.

Pluto Pluto is a on-device debugger for Android applications, which helps in inspection of HTTP requests/responses, capture Crashes and ANRs and manip

Mocklets 8 Aug 22, 2022