Code Monkey home page Code Monkey logo

kolley's Introduction

Kolley

Kolley是用 kotlin 实现,结合了VolleyOkHttp的一个RESTful网络请求框架。

Download

English

引用

repositories {
    jcenter()
    maven { url "https://jitpack.io" } // for PersistentCookieJar
}

compile 'com.ohmerhe.kolley:kolley:0.3.1'

0.3.1

  • 支持 Cookie 持久化储存
  • 修复上传中中文乱码的问题

0.3.0

  • 支持 Post 请求上传 Raw
  • 支持 upload 文件
  • 修复请求中没有传递 Header 的bug

标准HTTP请求

快速使用

初始化一次以后,可以很方便的发起一个网络请求。

Http.init(context) 

Http.get {
    url = "http://api.openweathermap.org/data/2.5/weather"
    onSuccess { bytes ->
        // handle data
    }
}    

参数

可以在params配置块中使用"key" - "value"的格式为网络请求置顶参数,每个参数占一行。

Http.get {
    ...
    params {
        "q" - "shanghai"
        "appid" - "xxxx"
    }
    ...
}

回调

回调也是类似配置的方式

Http.get {
    ...
    onStart {  }

    onSuccess { bytes ->
        // get data
    }

    onFail { error ->
        // handle error
    }

    onFinish {  }
    ...
}

请求Headers

添加headers的方式和params的方式很相似

Http.get {
    ...
    headers {
        "Content-Type" - "application/json"
    }
    ...
} 

取消

有两种方式可以取消网络请求

  • Request对象直接取消
val request = Http.get{...}
...
request.cancel
  • 使用tag的方式取消

你可以为每个网络请求打上一个tag,然后通过RequestQueue取消。

Http.get {
    ...
    tag = mTag
    ...
}
...
Http.getRequestQueue().cancelAll(tag)

上传文件

将需要上传的文件添加到 files 下面,参数形式和 params 一直,前面是 key,后面的 value 是对应文件的路径。 可支持多文件上传。

Http.upload{
    url = "http://192.168.199.110:3000"
    files {
        "image" - $imagePath
    }
}

如果上传文件需要带其他参数,也可以和其他网络请求一样添加在 params 下面。

获取图片

初始化

在你的application中直接初始化Image

Image.init(context)

Configuration

或者带上一些配置信息一起初始化

Image.init(this){
    // these values are all default value , you do not need specific them if you do not want to custom
    memoryCacheEnabled = true
    memoryCacheSize = (Runtime.getRuntime().maxMemory() / 8).toInt()
    diskCacheDir = File(cacheImagePath)
    diskCacheSize = 200 * 1024 * 1024 // default 200m size
    diskCacheEnabled = true
    compressFormat = Bitmap.CompressFormat.JPEG
    compressQuality = 80
}

显示图片

直接显示图片或者配置化显示

Image.display {
    url = "http://7xpox6.com1.z0.glb.clouddn.com/android_bg.jpg"
    imageView = mImageView
}
Image.display {
    url = "http://7xpox6.com1.z0.glb.clouddn.com/android_bg.jpg"
    imageView = mImageView
    options {
        // these values are all default value , you do not need specific them if you do not want to custom
        imageResOnLoading = R.drawable.default_image
        imageResOnLoading = R.drawable.default_image
        imageResOnFail = R.drawable.default_image
        decodeConfig = Bitmap.Config.RGB_565
        scaleType = ImageView.ScaleType.CENTER_CROP
        maxWidth = ImageDisplayOption.DETAULT_IMAGE_WIDTH_MAX
        maxHeight = ImageDisplayOption.DETAULT_IMAGE_HEIGHT_MAX
    }
}

下载图片

直接下载或者配置化下载。

Image.load {
    url = "http://7xpox6.com1.z0.glb.clouddn.com/android_bg.jpg"
    onSuccess { bitmap -> mImageView.setImageBitmap(bitmap)}
}
Image.load {
    url = "http://7xpox6.com1.z0.glb.clouddn.com/android_bg.jpg"
    options {
        scaleType = ImageView.ScaleType.CENTER_CROP
        maxWidth = ImageDisplayOption.DETAULT_IMAGE_WIDTH_MAX
        maxHeight = ImageDisplayOption.DETAULT_IMAGE_HEIGHT_MAX
    }
    onSuccess { bitmap -> _imageView2?.setImageBitmap(bitmap) }
    onFail { error ->
        log(error.toString())
    }
}

kolley's People

Contributors

dpmaycry avatar ohmerhe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kolley's Issues

如何设置超时时间?

有一个接口数据较多要5秒才返回,但是3秒左右就报TimeOutError了,能否自定义超时时间?

https post请求中header的ContentType无法替换

http中的post请求,在
Http.post{
headers {
"Content-Type" - "application/json"
}
}
中可以正确的替换ContentType,server端收到的是正确的值“application/json”
但是在https的请求中这样写的话,server端收到的ContentType却是“application/json;application/json;charset=utf8”,不会替换掉默认的contentType而是会添加上,不知道是不是我使用方式不对

0.3.1 build failed

i was trying to use the lastest version 0.3.1 on Android Studio 3.0 , it failed with error below.Failed to resolve: com.github.franmontiel:PersistentCookieJar:v1.0.1
Please let me know if any solution for this.
And when I tried out 0.3.0, build falied with this issue below:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

求帮助 No virtual method internalCache

不好意思,我是自学的android 在排错方面不太明白
想问下,下面这个报错什么情况:()

FATAL EXCEPTION: Thread-7
Process: cn.com.jkinfo.bilibilitest, PID: 27544
java.lang.NoSuchMethodError: No virtual method internalCache(Lokhttp3/OkHttpClient;)Lokhttp3/internal/InternalCache; in class Lokhttp3/internal/Internal; or its super classes (declaration of 'okhttp3.internal.Internal' appears in /data/app/cn.com.jkinfo.test-2/split_lib_dependencies_apk.apk)
at okhttp3.internal.huc.HttpURLConnectionImpl.newHttpEngine(HttpURLConnectionImpl.java:392)
at okhttp3.internal.huc.HttpURLConnectionImpl.initHttpEngine(HttpURLConnectionImpl.java:343)
at okhttp3.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
at okhttp3.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:263)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:264)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)

使用是参考示例的,应该没错吧:
package cn.com.jkinfo.test

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.util.Log
import com.ohmerhe.kolley.request.Http
import java.nio.charset.Charset

class BuildActivity : AppCompatActivity(),Parcelable {

var name : String = ""

val CREATOR: Parcelable.Creator<BuildActivity> = object : Parcelable.Creator<BuildActivity> {
    override fun createFromParcel(source: Parcel): BuildActivity {
        var ba : BuildActivity = BuildActivity()
        ba.name=source.readString()
        return BuildActivity()
    }

    override fun newArray(size: Int): Array<BuildActivity> {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

override fun writeToParcel(dest: Parcel?, flags: Int) {
    //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

override fun describeContents(): Int {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_build)


    Http.init(this)

    Http.post{
        url = "http://10.10.10.103:3001/api/post"
        raw = "{\"id\":\"1\"}"

        onSuccess {
            log("on success ${it.toString(Charset.defaultCharset())}")
        }
        onFail { error ->
            log("on fail ${error.toString()}")
        }
    }
}
fun log(text: String) {
    Log.d("BuildActivity", text)
}

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.