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之外, ...
随机推荐
- hdoj薛猫猫杯程序设计网络赛1003 球球大作战
思路: 二分,check函数不是很好写. 实现: 1. #include <bits/stdc++.h> using namespace std; typedef long long ll ...
- Objective-C Numbers
In Objective-C programming language, in order to save the basic data types like int, float, bool in ...
- Django之CSRF问题
1.csrf全称:cross site request forgery(跨站请求伪造),举例来讲,一个安全的网站A,一个恶意网站B,当你在A网站进行了登录后,这时候浏览器会保存你的cookie和ses ...
- SQL server 数据库基础语句 查询语句
这一章要学习查询语句 我看car这一数据 我们就开始打上 select *from car 条件修改 update 表名 set 列名1=值1 where 列名2=值2 //当列名2=值2时 ...
- sublime text 3中emmet常用技巧
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- struts2默认拦截器defaultStack
第一次使用Struts2.3.20,前台页面向后台传值,怎么总是提示值为null,查找半天原来是struts配置文件的action中忘记引入defaultStack拦截器了,所以即使Action中万事 ...
- POJ1077 八数码 BFS
BFS 几天的超时... A*算法不会,哪天再看去了. /* 倒搜超时, 改成顺序搜超时 然后把记录路径改成只记录当前点的操作,把上次的位置记录下AC..不完整的人生啊 */ #include < ...
- Google Colab调用cv2.imshow奔溃
当我在Google Colab运行如下代码 import cv2 import numpy as np image = cv2.imread('a.jpg') cv2.imshow('original ...
- The - Modcrab——使用贪心策略
一.题目信息 The - Modcrab 简单翻译一下:Vova有生命值h1,每次攻击值为a1,每瓶药水恢复生命值c1;Modcrab有生命值h2,每次攻击值为a2.在每个关卡开始,Vova有两种选择 ...
- ulrlib案例-爬取百度贴吧
1.任务需求 百度贴吧有很多主题,每个主题下的网页存在很多分页.爬取不同的主题,并下载每个主题下的多页网页. 输入贴吧名称,下载相应贴吧的多页网页,设置最多下载50页. 2.分析网页 访问不同的百度贴 ...