· 7 years ago · Apr 24, 2018, 09:42 AM
1class HttpRequest(context: Context) {
2
3 private val client: OkHttpClient
4 private var request: Request? = null
5 private var response: Response? = null
6 private val paramCommon: ParamCommon = ParamCommon(context)
7 private val sharePreferenceUtils: PreferenceManager
8
9 private val encodeDefault: String
10 private val deviceId: String
11 private val userAgent: String
12 private val timeRequest: Long
13 private val oauthToken: String
14 private val versionApp: String
15 private val authorizationCode: String
16
17 interface Callback {
18 fun onSuccess(message: String)
19
20 fun onFail(message: String)
21 }
22
23 interface DownloadCallback {
24 fun onSuccess(response: Response)
25
26 fun onFail()
27 }
28
29 init {
30 sharePreferenceUtils = PreferenceManager(context.applicationContext as Application)
31
32 encodeDefault = Constant.ENCODE_DEFAULT
33 deviceId = paramCommon.deviceId
34 userAgent = paramCommon.userAgent
35 timeRequest = paramCommon.timeRequest
36 versionApp = paramCommon.versionApp
37 oauthToken = paramCommon.encodeSH256(encodeDefault + deviceId + userAgent + timeRequest)
38 authorizationCode = sharePreferenceUtils.getAuthorizationCode()
39
40 client = OkHttpClient.Builder()
41 .connectTimeout(30, TimeUnit.SECONDS)
42 .writeTimeout(30, TimeUnit.SECONDS)
43 .readTimeout(30, TimeUnit.SECONDS)
44 .addInterceptor(HttpLoggingInterceptor().apply {
45 level = HttpLoggingInterceptor.Level.BODY
46 })
47 .build()
48 }
49
50 private fun statusRespone(json: String?): StatusRespone {
51 return Gson().fromJson<StatusRespone>(json, StatusRespone::class.java)
52 }
53
54 fun post(listParams: HashMap<String, String>, image: String, url: String, callback: Callback) {
55 var content: String? = null
56 val MEDIA_TYPE = MediaType.parse("image/png")
57 var fileName = "image"
58 if (image.endsWith("png")) {
59 MediaType.parse("image/png")
60 fileName += ".png"
61 } else {
62 MediaType.parse("image/jpeg")
63 fileName += ".jpg"
64 }
65
66 val multipartBody = MultipartBody.Builder()
67 multipartBody.setType(MultipartBody.FORM)
68
69 if (image.length > 3) {
70 multipartBody.addFormDataPart(KeyType.AVATAR, fileName,
71 RequestBody.create(MEDIA_TYPE, File(image)))
72 }
73
74 for ((key, values) in listParams) {
75 multipartBody.addFormDataPart(key, values)
76 }
77
78
79 val formBody = multipartBody.build()
80
81 val headersParam = HashMap<String, String>()
82 headersParam[KeyType.DEVICE_ID] = deviceId
83 headersParam[KeyType.USER_AGENT] = userAgent
84 headersParam[KeyType.TIME_REQUEST] = timeRequest.toString()
85 headersParam[KeyType.APP_VERSION] = versionApp
86 headersParam[KeyType.TOKEN] = oauthToken
87 if (authorizationCode != "")
88 headersParam[KeyType.AUTHORIZATION] = authorizationCode
89
90 val headers = Headers.of(headersParam)
91
92 request = Request.Builder()
93 .headers(headers)
94 .url(url)
95 .post(formBody)
96 .build()
97
98 Log.d(LOG, request!!.toString())
99
100 try {
101 response = client.newCall(request!!).execute()
102 content = response!!.body()!!.string()
103 val status = statusRespone(content)
104
105 if (response!!.isSuccessful) {
106 if (status.status) {
107 callback.onSuccess(content)
108 } else {
109 callback.onFail(status.errorCode!!)
110 }
111 } else {
112 callback.onFail(content)
113 }
114 } catch (e: Exception) {
115 e.printStackTrace()
116 callback.onFail(ERROR_DEFAULT)
117 }
118
119 }
120
121 fun post(listParams: HashMap<String, String>, url: String, callback: Callback) {
122 var content: String? = null
123
124 val formBuilder = FormBody.Builder()
125
126 for ((key, values) in listParams) {
127 formBuilder.add(key, values)
128 }
129
130 val formBody = formBuilder.build()
131
132 val headersParam = HashMap<String, String>()
133 headersParam[KeyType.DEVICE_ID] = deviceId
134 headersParam[KeyType.USER_AGENT] = userAgent
135 headersParam[KeyType.TIME_REQUEST] = timeRequest.toString()
136 headersParam[KeyType.APP_VERSION] = versionApp
137 headersParam[KeyType.TOKEN] = oauthToken
138 if (authorizationCode != "")
139 headersParam[KeyType.AUTHORIZATION] = authorizationCode
140
141 val headers = Headers.of(headersParam)
142
143 request = Request.Builder()
144 .headers(headers)
145 .url(url)
146 .post(formBody)
147 .build()
148
149 Log.d(LOG, request!!.toString())
150
151 try {
152 response = client.newCall(request!!).execute()
153 content = response!!.body()!!.string()
154 Log.e("onSuccess", "response $url $content")
155 val status = statusRespone(content)
156
157 if (response!!.isSuccessful) {
158 if (status.status) {
159 callback.onSuccess(content)
160 } else {
161 callback.onFail(status.errorCode!!)
162 }
163 } else {
164 callback.onFail(content)
165 }
166 } catch (e: Exception) {
167 e.printStackTrace()
168 callback.onFail(ERROR_DEFAULT)
169 }
170
171 }
172
173 operator fun get(listParams: HashMap<String, String>, url: String, callback: Callback) {
174 var content: String? = null
175
176 val urlBuilder = HttpUrl.parse(url)!!.newBuilder()
177
178 for ((key, values) in listParams) {
179 urlBuilder.addQueryParameter(key, values)
180 }
181
182 val urlWithParam = urlBuilder.build().toString()
183
184 val headersParam = HashMap<String, String>()
185 headersParam[KeyType.DEVICE_ID] = deviceId
186 headersParam[KeyType.USER_AGENT] = userAgent
187 headersParam[KeyType.TIME_REQUEST] = timeRequest.toString()
188 headersParam[KeyType.APP_VERSION] = versionApp
189 headersParam[KeyType.TOKEN] = oauthToken
190 if (authorizationCode != "")
191 headersParam[KeyType.AUTHORIZATION] = authorizationCode
192
193 val headers = Headers.of(headersParam)
194
195 request = Request.Builder()
196 .headers(headers)
197 .url(urlWithParam)
198 .build()
199
200 try {
201 response = client.newCall(request!!).execute()
202 content = response!!.body()!!.string()
203 Log.e("onSuccess", "response $url $content")
204 val status = statusRespone(content)
205
206 if (response!!.isSuccessful) {
207 if (status.status) {
208 callback.onSuccess(content)
209 } else {
210 callback.onFail(status.errorCode!!)
211 }
212 } else {
213 callback.onFail(content)
214 }
215 } catch (e: Exception) {
216 e.printStackTrace()
217 callback.onFail(ERROR_DEFAULT)
218 }
219
220 }
221
222 fun downloadFile(url: String, callback: DownloadCallback) {
223 try {
224 request = Request.Builder()
225 .url(url)
226 .get()
227 .build()
228 response = client.newCall(request!!).execute()
229
230 if (response!!.isSuccessful) {
231 callback.onSuccess(response!!)
232 } else {
233 callback.onFail()
234 }
235 } catch (e: IOException) {
236 e.printStackTrace()
237 callback.onFail()
238 }
239
240 }
241
242 companion object {
243 private const val LOG = "TTTP"
244 private const val ERROR_DEFAULT = "1000"
245 }
246
247}