EasyHttp

EasyHttp is a Kotlin DSL network request framework based on OkHttp encapsulation

Making the address

function

  • [x] Supports HTTP GET/POST/PUT/DELETE
  • [x] File Download (with progress)
  • [x] File upload (multipart/form-data)(with progress)
  • [x] RxJava2.0 request response support
  • [x] Support Gson automatic serialization and Parser custom extension
  • [x] Supports custom configuration of OkHttpClient
  • [x] DSL configuration request

directory

  • Installation instructions
  • The Client configuration
  • Ordinary request
  • File upload
  • File download
  • RxJava compatible
  • A custom Parser
  • contribution
  • Thank you

Installation instructions

Gradle:

  1. From build.gradle(Project:XXXX) add:
	allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io'}}}Copy the code
  1. Add to build. Gradle (Module:app) dependencies:
	dependencies {
		  compile 'com.github.Rayhahah:EasyHttp:{release_version}'
	}
Copy the code

The Client configuration

Configure global OkHttpClient

/** * build OkHttpClient */ EClient {// configure default baseUrl baseUrl ="http://mall.rayhahah.com/"// Configure the default request typetype = TYPE.METHOD_POST
                 timeUnit = TimeUnit.SECONDS
                 connectTimeout = 10
                 readTimeout = 10
                 writeTimeout = 10
                 interceptors()
                 networkInterceptors()
                 retryOnConnectionFailure = trueParser = null // Configure the global common request header = {"custom_head"("rayhahah")}}Copy the code

Or pass in the custom OkHttpClient directly

EClient(client: OkHttpClient)
Copy the code

GET/POST/PUT/DELETE request

  • client: Used in this requestOkHttpClientIf no value is specified, the preceding value is used by defaultEClientConfiguration of theOkHttpClientobject
  • type: Distinguishes request types,TYPE.METHOD_GETTYPE.METHOD_POST,TYPE.METHOD_PUTTYPE.METHOD_DELETE
  • data: Parameters carried by the request,"key"("value")
  • header: Request header parameter,"key"("value")
  • go(success,fail,progress): Sends requests, callbacks are in the main thread
    • success = {data:Response->}: The callback was requested successfully
    • fail = {call:Call,e:Exception -> }: Request failed callback
    • progess = {value:Float,total:Long -> }: The request process is returned and the uploaded file can be viewed

A normal request with detailed configuration is as follows:

 EHttp {
		    client = okHttpClient
            baseUrl = "http://mall.rayhahah.com/"
            src = "user/login.do"
            type = TYPE.METHOD_GET
            data = {
                "username"(username)
                "password"(password)
            }
            header = {
                "cache-Control"("no-cache")
            }

        }.go(success,fail,progress)
Copy the code

Next, make it simple:

EHttp{
  baseUrl = "http://mall.rayhahah.com/"
  src = "user/login.do"
 type = TYPE.METHOD_GET
 data = {
       "username"(username)
       "password"(password)
        }
}.go{data:Response -> }

Copy the code

Or a simple request can do this

EGet(url:String,params:HashMap<String,String>())
	.go{data:Response->}

EPost(url:String,params:HashMap<String,String>())
	.go{data:Response->}
Copy the code

File upload

  • file: Uploaded file
    • "Key "(" type of File uploaded", File())
    • "Key "(HttpFile(" type of uploaded File ",ArrayList<File>())
     EHttp {
            baseUrl = "http://mall.rayhahah.com/"
            src = "easysport/user/update_cover.do"
            type = TYPE.METHOD_POST
            data = {
                "username"(username)
                "password"(password) file = {// Upload a file"upload_file"FILE_TYPE_MULTIPART, cover) val fileList = ArrayList<File>() filelist.add (File() filelist.add (File())"1.txt"))
                    fileList.add(File("2.txt"))
                    fileList.add(File("3.txt"))
                    "upload"(HttpFile(Files.FILE_TYPE_MULTIPART, fileList))
                }
            }
            header = {
                "cache-Control"("no-cache")
            }

        }.go(success, fail, progress)

Copy the code

File download

  EHttp {
                baseUrl = "http://thing.rayhahah.com/version/EasySport_1.1.4.apk"
                download = {
                    fileDir = FileUtils.getRootFilePath() + "EasyHttp/images"
                    fileName = "test.apk"} }.download(success={ data: File -> data.log() }, fail={ call: Call, exception: Exception -> }, progress={ value: Float, total: Long - > value. The log () total. The log ()}) / / a little bit more simple ~ ~ ~ ~ EDownload (url, fileDir, : String, fileName: String, success, and fail, progress)Copy the code

RxJava compatible

As long as GO or RX can return Observable

O ( ̄▽ ̄)ブ ブ

EHttp {
            baseUrl = "http://mall.rayhahah.com/"
            src = "user/login.do"
            type = method
            data = {
                "username"(username)
                "password"(password)
            }
            header = {
                "cache-Control"("no-cache") } }.rx(progress = { value, total -> }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { t: Response -> t.log() mTvTest.setText(t.body()? .string()) }Copy the code

A custom Parser

JsonParser is provided by default and internally uses Gson to automatically serialize JSON strings. We can also customize Parser to do our own data preprocessing

This process occurs in child threads, where we can parse some particularly complex request return data

Implement the Parser interface and return data according to your own needs.

Ps: The return value here must be consistent with the generic type at request time

Class CustomParser: Parser {/** * Data Parser */ Override fun parse(response: response): Any? {returnresponse.body()? String ()} /** * override fun isCanParse(response: response): Boolean {return true} / / override fun unParse(response: response): Any? {returnresponse.body()? .string() } }Copy the code

contribution

If you have any problems using EasyHttp, please raise Issues. We welcome all of you to contribute your wisdom to EasyHttp and welcome all of you to Fork and Pull requests. Like to a star bai, O ( ̄▽ ̄)ブ ブ

Thank you

  • OkHttp
  • RxJava