AsyncHttpClient简介与实例代码

AsyncHttpClient版本再1.9前后有有较大的差异,因为内部采用Netty进行网络请求,因此异步的性能比HttpClient更加的优秀
Netty:是一个异步事件驱动的网络应用框架,用于快速开发可维护的高性能服务器和客户端,它是对JDK的NIO(非阻塞IO)进行了封装,让使用变的简单,安全。
关于Netty详细的简单介绍请参考:https://www.jianshu.com/p/a4e03835921a
使用async-http-client.jar进行get和post请求的简单实例:

依赖jir包
依赖jar包说明:1.9前后的api还是存在一些差异的,比如set参数的api的变化等。


    com.ning
    async-http-client
    1.8.17

gradle

compile group: 'com.ning', name: 'async-http-client', version: '1.8.17'

Kotlin(可以与java相互转化)示例代码

package com.rakuten.id.id2.v2.utils

import com.ning.http.client.*
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit

object HttpClientUtil {
    @Throws
    fun httpPost(asyncHttpClient: AsyncHttpClient, url: String, params: Map): Response? {
        val builder = asyncHttpClient.preparePost(url)
                .setBodyEncoding("UTF-8")

        params?.entries?.forEach { (t, u) -> builder.addParameter(t, u) }

        return builder.execute()?.get(10, TimeUnit.SECONDS)
    }

    @Throws
    fun httpGet(asyncHttpClient: AsyncHttpClient, url: String, params: Map?): Future? {
        val builder = asyncHttpClient.prepareGet(url)
                .setBodyEncoding("UTF-8")

        params?.entries?.forEach { (t, u) -> builder.addParameter(t, u) }
        return builder.execute()
    }

    @Throws
    fun httpPostJson(url: String, header: Map, body: String): Response? {
        val asyncHttpClient = AsyncHttpClient()
        val builder = asyncHttpClient.preparePost(url)
                .setBodyEncoding("UTF-8")
                .setBody(body)
        header.forEach { (t, u) -> builder.addHeader(t, u) }

        val response = builder.execute()?.get(10, TimeUnit.SECONDS)
        asyncHttpClient.close()
        return response
    }
}

 

调用:

fun useHttp(): Boolean{

val response = HttpClientUtil
                    .httpPostJson(ReadConfItako.getInstance().getProperty("blacklist.api.url"), mapOf(), body.toString())
            return response?.statusText.equals("ok")
}

 

你可能感兴趣的:(java,kotiln)