package jp.co.gunmabank.util

import android.os.Handler
import android.os.Looper
import com.google.gson.Gson
import com.google.gson.JsonParseException
import com.google.gson.internal.`$Gson$Types`
import com.squareup.okhttp.*
import io.fabric.sdk.android.services.common.AbstractSpiCall.DEFAULT_TIMEOUT
import jp.co.gunmabank.minefocus.BuildConfig
import java.io.IOException
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.net.CookieManager
import java.net.CookiePolicy
import java.net.Proxy
import jp.co.gunmabank.util.TrustAllCerts
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import javax.net.ssl.*
import javax.xml.datatype.DatatypeConstants.SECONDS
import io.fabric.sdk.android.services.settings.IconRequest.build
import com.squareup.okhttp.RequestBody
import jp.co.gunmabank.common.Common
import io.fabric.sdk.android.services.settings.IconRequest.build
import io.fabric.sdk.android.services.settings.IconRequest.build /**
* 非同時OkHttpのフォームに基づいてを提出 * Created by wangsai on 2017/05/12.
*/ object OkHttpUtil { private var mOkHttpClient: OkHttpClient
private val mDelivery: Handler
private val mGson: Gson
private var mInstance: OkHttpUtil? = null init {
mOkHttpClient = OkHttpClient()
//cookie enabled
mOkHttpClient.cookieHandler = CookieManager(null, java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER) mDelivery = Handler(Looper.getMainLooper())
mGson = Gson()
if (mInstance == null) {
synchronized(OkHttpUtil::class.java) {
if (mInstance == null) {
mInstance = OkHttpUtil
}
}
}
} /**
* 非同時OkHttpのフォームに基づいてを提出 * @param url
* *
* @param callback
* *
* @param sendData
* *
* @throws IOException
*/
@Throws(IOException::class)
private fun postFormDataAsyn(url: String, callback: ResultCallback<*>, sendData: String, sendLinkData: String, name: String, linkname: String) {
val request = buildMultipartFormRequest(url, sendData, sendLinkData, name, linkname)
deliveryResult(callback, request)
} @Throws(IOException::class)
private fun postJsonDataAsyn(url: String, callback: ResultCallback<*>, sendData: String) {
val request = buildPostJosnRequest(url, sendData)
deliveryResult(callback, request)
} /**
* データを整理 * @param url
* *
* @param sendData
* *
* @return
*/
private fun buildMultipartFormRequest(url: String, sendData: String, sendLinkData: String, name: String, linkname: String): Request {
var boundary = "--AlamofireBoundary" + Common.randomFor4Num(8)
val builder = MultipartBuilder(boundary).type(MultipartBuilder.FORM)
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + name + "\""), RequestBody.create(MediaType.parse("application/json; charset=utf-8"), sendData))
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + linkname + "\""), RequestBody.create(MediaType.parse("application/json; charset=utf-8"), sendLinkData))
val requestBody = builder.build()
return Request.Builder().url(url).post(requestBody).build()
} private fun buildPostJosnRequest(url: String, sendData: String): Request { val request = Request.Builder().url(url).post(RequestBody.create(
MediaType.parse("application/json; charset=utf-8"),
sendData)).build()
return request
} /**
* 結果を処理 * @param callback
* *
* @param request
*/
private fun deliveryResult(callback: ResultCallback<*>, request: Request) {
var dnpSendmsg = ""
mOkHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(request: Request, e: IOException) {
dnpSendmsg = request.tag().toString()
sendFailedStringCallback(dnpSendmsg, request, e, callback)
} override fun onResponse(response: Response) {
try {
val str = response.body().string()
if (callback.mType === String::class.java) {
sendSuccessResultCallback(str, callback)
} else {
//TODO mGson
}
} catch (e: IOException) {
sendFailedStringCallback(dnpSendmsg, response.request(), e, callback)
} catch (e: JsonParseException) {
sendFailedStringCallback(dnpSendmsg, response.request(), e, callback)
} }
})
} private fun sendFailedStringCallback(dnpSendmsg: String, request: Request, e: Exception, callback: ResultCallback<*>) {
mDelivery.post {
callback?.onError(dnpSendmsg, request, e)
}
} private fun sendSuccessResultCallback(any: String, callback: ResultCallback<*>) {
mDelivery.post {
callback?.onResponse(any)
}
} abstract class ResultCallback<T> {
internal var mType: Type init {
mType = getSuperclassTypeParameter(javaClass)
} abstract fun onError(dnpSendmsg: String, request: Request, e: Exception) abstract fun onResponse(str: String) companion object { internal fun getSuperclassTypeParameter(subclass: Class<*>): Type {
val superclass = subclass.genericSuperclass
if (superclass is Class<*>) {
throw RuntimeException("Missing type parameter.")
}
val parameterized = superclass as ParameterizedType
return `$Gson$Types`.canonicalize(parameterized.actualTypeArguments[0])
}
}
} /**
* 非同時OkHttpのフォームに基づいてを提出 * @param url
* *
* @param callback
* *
* @param sendData
* *
* @throws IOException
*/
fun postFormAsyn(url: String, callback: ResultCallback<*>, sendData: String, sendLinkData: String, name: String, linkname: String) {
mOkHttpClient = OkHttpClient() mOkHttpClient.setConnectTimeout(100, TimeUnit.SECONDS)
mOkHttpClient.setReadTimeout(100, TimeUnit.SECONDS)
//cookie enabled
mOkHttpClient.cookieHandler = CookieManager(null, java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER)
mInstance!!.postFormDataAsyn(url, callback, sendData, sendLinkData, name, linkname)
} /**
* 非同時OkHttpのフォームに基づいてを提出 * @param url
* *
* @param callback
* *
* @param sendData
* *
* @throws IOException
*/
fun postFormAsynForAUth(url: String, callback: ResultCallback<*>, sendData: String, sendLinkData: String, name: String, linkname: String, usename: String, usepassword: String) {
mOkHttpClient = OkHttpClient()
if (BuildConfig.FLAVOR == "stg" || BuildConfig.FLAVOR == "jp") {
mOkHttpClient.authenticator = object : Authenticator {
override fun authenticate(proxy: Proxy?, response: Response?): Request {
val credential = Credentials.basic(usename, usepassword)
return response!!.request().newBuilder()
.header("Authorization", credential)
.build()
} override fun authenticateProxy(proxy: Proxy?, response: Response?): Request? {
return null
}
}
mOkHttpClient.sslSocketFactory = createSSLSocketFactory()
mOkHttpClient.hostnameVerifier = HostnameVerifier { hostname, session -> true }
}
mOkHttpClient.setConnectTimeout(100, TimeUnit.SECONDS)
mOkHttpClient.setReadTimeout(100, TimeUnit.SECONDS)
mOkHttpClient.setWriteTimeout(100, TimeUnit.SECONDS)
//cookie enabled
mOkHttpClient.cookieHandler = CookieManager(null, java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER)
mInstance!!.postFormDataAsyn(url, callback, sendData, sendLinkData, name, linkname)
} fun postJsonAsynForAUth(url: String, callback: ResultCallback<*>, sendData: String, usename: String, usepassword: String) {
mOkHttpClient = OkHttpClient()
if (BuildConfig.FLAVOR == "stg" || BuildConfig.FLAVOR == "jp") {
mOkHttpClient.authenticator = object : Authenticator {
override fun authenticate(proxy: Proxy?, response: Response?): Request {
val credential = Credentials.basic(usename, usepassword)
return response!!.request().newBuilder()
.header("Authorization", credential)
.build()
} override fun authenticateProxy(proxy: Proxy?, response: Response?): Request? {
return null
}
} mOkHttpClient.sslSocketFactory = createSSLSocketFactory()
mOkHttpClient.hostnameVerifier = HostnameVerifier { hostname, session -> true }
}
mOkHttpClient.setConnectTimeout(600, TimeUnit.SECONDS)
mOkHttpClient.setReadTimeout(600, TimeUnit.SECONDS)
mOkHttpClient.setWriteTimeout(600, TimeUnit.SECONDS)
//cookie enabled
mOkHttpClient.cookieHandler = CookieManager(null, java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER)
mInstance!!.postJsonDataAsyn(url, callback, sendData)
} private fun createSSLSocketFactory(): SSLSocketFactory? {
var ssfFactory: SSLSocketFactory? = null try {
val sc = SSLContext.getInstance("TLS")
sc.init(null, arrayOf<TrustManager>(TrustAllCerts()), SecureRandom()) ssfFactory = sc.socketFactory
} catch (e: Exception) {
} return ssfFactory
}
}

OkHttpUtil的更多相关文章

  1. OKHttpUtil工具类

    导入jar包下载链接 http://square.github.io/okhttp/ package com.common.util; import java.io.IOException; impo ...

  2. 简单的OkHttp使用介绍

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  3. OkHttp使用教程

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  4. 关于okhttp

    本文出处:http://www.tuicool.com/articles/rArq63u 为什么需要一个HTTP库 Android系统提供了两种HTTP通信类,HttpURLConnection和Ht ...

  5. OkHttp使用介绍

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/4001708.html 为什么需要一个HTTP库 Androi ...

  6. OkHttp使用全解析(转)。

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  7. OkHttp 源码分析

    在工作中用到封装HTTP传输的OkHTTP,OkHttp是相对成熟的解决方案,同时也是开源项目.本文将从源码角度看下OkHttp是如何实现一些网络操作的. HTTP GET: OkHttpClient ...

  8. android 中对于采用okhttp时获取cookie并放入webview实现跳过登陆显示页面的功能

    最近项目需要将网页的一些信息展示到app当中,由于采用的是okhttp进行网络的访问,并采用了cookie对于每次的访问请求都做了验证,所以在加入webview显示网页的时候会需要进行一下验证,为了跳 ...

  9. 如何使用MVP模式搭建我们的Android应用?

    听到很多人在讨论MVVM,我自己早些时候也写过一篇介绍MVVM的文章(玩转Android之MVVM开发模式实战,炫酷的DataBinding!),实际上,在Android开发领域中,除了MVVM之外, ...

随机推荐

  1. 用好js与nodejs中的try...catch

    对异常的捕获和处理是提高程序鲁棒性的一个重要方式,即使在javascript/nodejs等看似“很难写出bug”的弱类型语言里,异常捕获处理仍至关重要,这主要是因为: 1.在一个代码块里,如果程序运 ...

  2. 网页设计必备工具 firefox Web Developer插件 CSS工具组教程

    该插件在火狐浏览器中安装.Web Developer 插件强大的功能超乎你的想象,用于CSS网页布局开发调试只是它强大功能的一部分,对于网络程序的开发也提供了非常强大的辅助设计功能,我们不将它完全的展 ...

  3. 解决常见SVN冲突问题(转)

    转自:http://www.w3cfuns.com/blog-5443287-5403523.html 一个大项目在开发中可能会拆分成几个小项目,分别分去,同时共通的部分再由人做,做完后再统一合并.同 ...

  4. LINUX提高openfire并发数(网上收集)

    谷歌博客地址:http://tsaiquinn.blogspot.com/2014/10/linuxopenfire.html 影响连接数的元素包含三种:1)Linux的系统参数2)进程自身可以创建的 ...

  5. 洛谷 P1774 最接近神的人_NOI导刊2010提高(02)

    题目描述 破解了符文之语,小FF开启了通往地下的道路.当他走到最底层时,发现正前方有一扇巨石门,门上雕刻着一幅古代人进行某种活动的图案.而石门上方用古代文写着“神的殿堂”.小FF猜想里面应该就有王室的 ...

  6. Hibernate查询方式汇总

    Hibernate总的来说共有三种查询方式:HQL.QBC和SQL三种.但是细分可以有如下几种: 一.HQL查询方式    这一种我最常用,也是最喜欢用的,因为它写起来灵活直观,而且与所熟悉的SQL的 ...

  7. Shell脚本之for循环、while循环,if语句、case语句

    1. for循环一般格式: 格式1: for((条件)) do 动作 done 格式2: for 变量名 in 范围 do 动作 done1234567891011121314实验:##1. 输出数字 ...

  8. java HttpServletRequest 重复流读取

    在用reset接口的时候,常常会使用request.getInputStream()方法,但是流只能读取一次,一旦想要加上一个过滤器用来检测用户请求的数据时就会出现异常.   在过滤器中通过流读取出用 ...

  9. Jarvis OJ-level3

    使用ret2libc攻击方法绕过数据执行保护 from pwn import* conn = remote("pwn2.jarvisoj.com",9879) elf = ELF( ...

  10. easyui树节点拖拽排序的存储过程

    easyui树的拖拽排序功能 easyui树中有拖拽功能 树结构如下: 一个行政区域对应一个单位,一个单位对应多个部门,每个部门下有相关人员,功能要求: (1)行政区域没有子节点,点击text加载部门 ...