OkHttpUtil
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的更多相关文章
- OKHttpUtil工具类
导入jar包下载链接 http://square.github.io/okhttp/ package com.common.util; import java.io.IOException; impo ...
- 简单的OkHttp使用介绍
Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...
- OkHttp使用教程
Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...
- 关于okhttp
本文出处:http://www.tuicool.com/articles/rArq63u 为什么需要一个HTTP库 Android系统提供了两种HTTP通信类,HttpURLConnection和Ht ...
- OkHttp使用介绍
版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/4001708.html 为什么需要一个HTTP库 Androi ...
- OkHttp使用全解析(转)。
Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...
- OkHttp 源码分析
在工作中用到封装HTTP传输的OkHTTP,OkHttp是相对成熟的解决方案,同时也是开源项目.本文将从源码角度看下OkHttp是如何实现一些网络操作的. HTTP GET: OkHttpClient ...
- android 中对于采用okhttp时获取cookie并放入webview实现跳过登陆显示页面的功能
最近项目需要将网页的一些信息展示到app当中,由于采用的是okhttp进行网络的访问,并采用了cookie对于每次的访问请求都做了验证,所以在加入webview显示网页的时候会需要进行一下验证,为了跳 ...
- 如何使用MVP模式搭建我们的Android应用?
听到很多人在讨论MVVM,我自己早些时候也写过一篇介绍MVVM的文章(玩转Android之MVVM开发模式实战,炫酷的DataBinding!),实际上,在Android开发领域中,除了MVVM之外, ...
随机推荐
- CF1060C Maximum Subrectangle
思路: 不难发现,对矩阵中的数字求和实际上是先分别对a,b两个数列中对应子段的元素求和再相乘.题目是要求在和不超过给定值的情况下使选出的矩阵面积最大.我们反其道而行之,考虑在子段长度一定的情况下,和最 ...
- POJ 1741 Tree (树的分治,树的重心)
题意:给一棵树,n个节点,给定一个数k,求任意满足dist(a,b)<=k的点对的数量. 思路: 这道题的思路比较简单,但是细节很多. 此题可以用分治法,如何分治? (1)如果path(a,b) ...
- (转)MyBatis框架的学习(六)——MyBatis整合Spring
http://blog.csdn.net/yerenyuan_pku/article/details/71904315 本文将手把手教你如何使用MyBatis整合Spring,这儿,我本人使用的MyB ...
- Gym 100342F Move to Front (树状数组动态维护和查询)
用树状数组动态和查询修改排名. 树状数组可以很方便地查询前缀和,那么可以利用这一特点,记录一个点在树状数组里最后一次出现的位置, 查询出这个位置,就可以知道这个点的排名了.更改这个点的排名的时候只要把 ...
- UVA 11400 Lighting System Design 照明系统设计
首先是一个贪心,一种灯泡要么全都换,要么全都不换. 先排序,定义状态d[i]为前面i种灯泡的最小花费,状态转移就是从d[j],j<i,加上 i前面的j+1到i-1种灯泡换成i的花费. 下标排序玩 ...
- Android(java)学习笔记140:常用的对话框
一.常见对话框属性: 1. AlertDialog.Builder属性 • setTitle: 为对话框设置标题 :• setIcon : 为对话框设置图标:• setMessage: 为对话框设置 ...
- 多源最短路径floyd
#include<iostream> #define INF 105 using namespace std; int main() { ][],mark,x,y,g; while(cin ...
- python中return和yield
def wx(): a = 'wx' b = '无邪' return a, b print(wx()) print(type(wx())) -----------执行结果--------------- ...
- vue 动态合并单元格、并添加小计合计功能
1.效果图 2.后台返回数据格式(平铺式) 3.后台返回数据后,整理所需要展示的属性存储到(items)数组内 var obj = { "id": curItems[i].id, ...
- shell脚本,awk实现行列转换
[root@localhost study]# cat file 张三 语文 张三 数学 李四 语文 李四 数学 王五 语文 王五 数学 王五 英语 怎么实现为下面的排序??? 语文 数学 语文 数学 ...