OSDN Git Service

Thetaのプレビューまで。
[gokigen/A01c.git] / wear / src / main / java / jp / sfjp / gokigen / a01c / utils / SimpleHttpClient.kt
1 package jp.sfjp.gokigen.a01c.utils
2
3 import android.graphics.Bitmap
4 import android.graphics.BitmapFactory
5 import android.util.Log
6 import java.io.*
7 import java.net.HttpURLConnection
8 import java.net.URL
9
10 class SimpleHttpClient
11 {
12     /**
13      *
14      *
15      *
16      */
17     fun httpGet(url: String, timeoutMs: Int): String
18     {
19         var inputStream : InputStream? = null
20         var replyString = ""
21         var timeout = timeoutMs
22         if (timeoutMs < 0)
23         {
24             timeout = DEFAULT_TIMEOUT
25         }
26
27         //  HTTP GETメソッドで要求を投げる
28         try
29         {
30             val httpConn = URL(url).openConnection() as HttpURLConnection
31             try
32             {
33                 httpConn.requestMethod = "GET"
34                 httpConn.connectTimeout = timeout
35                 httpConn.readTimeout = timeout
36                 httpConn.connect()
37                 val responseCode = httpConn.responseCode
38                 if (responseCode == HttpURLConnection.HTTP_OK)
39                 {
40                     inputStream = httpConn.inputStream
41                 }
42                 if (inputStream == null)
43                 {
44                     Log.w(TAG, "httpGet: Response Code Error: $responseCode: $url")
45                     return ("")
46                 }
47             }
48             catch (ee : Exception)
49             {
50                 Log.w(TAG, "httpGet: " + url + "  " + ee.message)
51                 ee.printStackTrace()
52                 httpConn.disconnect()
53                 return ("")
54             }
55         }
56         catch (e: Exception)
57         {
58             Log.w(TAG, "httpGet(2): " + url + "  " + e.message)
59             e.printStackTrace()
60             return ("")
61         }
62
63         // 応答を確認する
64         try
65         {
66             val responseBuf = StringBuilder()
67             val reader = BufferedReader(InputStreamReader(inputStream))
68             var c: Int
69             while (reader.read().also { c = it } != -1)
70             {
71                 responseBuf.append(c.toChar())
72             }
73             replyString = responseBuf.toString()
74             reader.close()
75         }
76         catch (e: Exception)
77         {
78             Log.w(TAG, "httpGet: exception: " + e.message)
79             e.printStackTrace()
80         }
81         finally
82         {
83             try
84             {
85                 inputStream.close()
86             }
87             catch (e: Exception)
88             {
89                 e.printStackTrace()
90             }
91         }
92         return (replyString)
93     }
94
95     /**
96      *
97      *
98      *
99      */
100     fun httpGetBytes(url: String, setProperty: Map<String, String>?, timeoutMs: Int, callback: IReceivedMessageCallback)
101     {
102         httpCommandBytes(url, "GET", null, setProperty, null, timeoutMs, callback)
103     }
104
105     /**
106      *
107      *
108      *
109      */
110     fun httpPostBytes(url: String, postData: String?, setProperty: Map<String, String>?, timeoutMs: Int, callback: IReceivedMessageCallback)
111     {
112         httpCommandBytes(url, "POST", postData, setProperty, null, timeoutMs, callback)
113     }
114
115     private fun httpCommandBytes(url: String, requestMethod: String, postData: String?, setProperty: Map<String, String>?, contentType: String?, timeoutMs: Int, callback: IReceivedMessageCallback)
116     {
117         var inputStream: InputStream? = null
118         var timeout = timeoutMs
119         if (timeoutMs < 0)
120         {
121             timeout = DEFAULT_TIMEOUT
122         }
123
124         //  HTTP メソッドで要求を送出
125         try
126         {
127             val httpConn = URL(url).openConnection() as HttpURLConnection
128             httpConn.requestMethod = requestMethod
129             if (setProperty != null)
130             {
131                 for (key in setProperty.keys)
132                 {
133                     val value = setProperty[key]
134                     httpConn.setRequestProperty(key, value)
135                 }
136             }
137             if (contentType != null)
138             {
139                 httpConn.setRequestProperty("Content-Type", contentType)
140             }
141             httpConn.connectTimeout = timeout
142             httpConn.readTimeout = timeout
143             if (postData == null)
144             {
145                 httpConn.connect()
146             }
147             else
148             {
149                 httpConn.doInput = true
150                 httpConn.doOutput = true
151                 val outputStream = httpConn.outputStream
152                 val writer = OutputStreamWriter(outputStream, "UTF-8")
153                 writer.write(postData)
154                 writer.flush()
155                 writer.close()
156                 outputStream.close()
157             }
158             val responseCode = httpConn.responseCode
159             if (responseCode == HttpURLConnection.HTTP_OK)
160             {
161                 inputStream = httpConn.inputStream
162             }
163             if (inputStream == null)
164             {
165                 Log.w(TAG, " http $requestMethod Response Code Error: $responseCode: $url")
166                 callback.onErrorOccurred(NullPointerException())
167                 callback.onCompleted()
168                 return
169             }
170
171             // 応答を確認する
172             try
173             {
174                 var contentLength = httpConn.contentLength
175                 if (contentLength < 0)
176                 {
177                     // コンテンツ長が取れない場合の処理...
178                     try
179                     {
180                         val headers = httpConn.headerFields
181                         // コンテンツ長さが取れない場合は、HTTP応答ヘッダから取得する
182                         val valueList = headers["X-FILE_SIZE"]
183                         try
184                         {
185                             if (valueList != null)
186                             {
187                                 contentLength = getValue(valueList).toInt()
188                             }
189                         }
190                         catch (ee: Exception)
191                         {
192                             ee.printStackTrace()
193                         }
194                     }
195                     catch (e: Exception)
196                     {
197                         e.printStackTrace()
198                     }
199                 }
200                 val buffer = ByteArray(BUFFER_SIZE)
201                 var readBytes = 0
202                 var readSize = inputStream.read(buffer, 0, BUFFER_SIZE)
203                 while (readSize != -1)
204                 {
205                     callback.onReceive(readBytes, contentLength, readSize, buffer)
206                     readBytes += readSize
207                     readSize = inputStream.read(buffer, 0, BUFFER_SIZE)
208                 }
209                 Log.v(TAG, "RECEIVED $readBytes BYTES. (contentLength : $contentLength)")
210                 inputStream.close()
211             }
212             catch (e: Exception)
213             {
214                 Log.w(TAG, "httpGet: exception: " + e.message)
215                 e.printStackTrace()
216                 callback.onErrorOccurred(e)
217             }
218             finally
219             {
220                 try
221                 {
222                     inputStream.close()
223                 }
224                 catch (e: Exception)
225                 {
226                     e.printStackTrace()
227                 }
228             }
229         }
230         catch (e: Exception)
231         {
232             Log.w(TAG, "http " + requestMethod + " " + url + "  " + e.message)
233             e.printStackTrace()
234             callback.onErrorOccurred(e)
235             callback.onCompleted()
236             return
237         }
238         callback.onCompleted()
239     }
240
241
242     private fun getValue(valueList: List<String>): String
243     {
244         // 応答ヘッダの値切り出し用...
245         var isFirst = true
246         val values = StringBuilder()
247         for (value in valueList)
248         {
249             values.append(value)
250             if (isFirst)
251             {
252                 isFirst = false
253             }
254             else
255             {
256                 values.append(" ")
257             }
258         }
259         return values.toString()
260     }
261
262     fun httpGetBitmap(url: String, setProperty: Map<String, String>?, timeoutMs: Int): Bitmap?
263     {
264         return (httpCommandBitmap(url, "GET", null, setProperty, null, timeoutMs))
265     }
266
267     /**
268      *
269      *
270      *
271      */
272     fun httpPostBitmap(url: String, postData: String?, timeoutMs: Int): Bitmap?
273     {
274         return (httpCommandBitmap(url, "POST", postData, null, null, timeoutMs))
275     }
276
277     /**
278      *
279      *
280      *
281      */
282     private fun httpCommandBitmap(url: String, requestMethod: String, postData: String?, setProperty: Map<String, String>?, contentType: String?, timeoutMs: Int): Bitmap?
283     {
284         //var httpConn: HttpURLConnection? = null
285         var inputStream: InputStream? = null
286         //var outputStream: OutputStream? = null
287         //var writer: OutputStreamWriter? = null
288         var bmp: Bitmap? = null
289         var timeout = timeoutMs
290         if (timeoutMs < 0)
291         {
292             timeout = DEFAULT_TIMEOUT
293         }
294
295         //  HTTP メソッドで要求を送出
296         try
297         {
298             val httpConn = URL(url).openConnection() as HttpURLConnection
299             httpConn.requestMethod = requestMethod
300             if (setProperty != null)
301             {
302                 for (key in setProperty.keys)
303                 {
304                     val value = setProperty[key]
305                     httpConn.setRequestProperty(key, value)
306                 }
307             }
308             if (contentType != null)
309             {
310                 httpConn.setRequestProperty("Content-Type", contentType)
311             }
312             httpConn.connectTimeout = timeout
313             httpConn.readTimeout = timeout
314             if (postData == null)
315             {
316                 httpConn.connect()
317             }
318             else
319             {
320                 httpConn.doInput = true
321                 httpConn.doOutput = true
322                 val outputStream = httpConn.outputStream
323                 val writer = OutputStreamWriter(outputStream, "UTF-8")
324                 writer.write(postData)
325                 writer.flush()
326                 writer.close()
327                 outputStream.close()
328             }
329             val responseCode = httpConn.responseCode
330             if (responseCode == HttpURLConnection.HTTP_OK)
331             {
332                 inputStream = httpConn.inputStream
333                 if (inputStream != null)
334                 {
335                     bmp = BitmapFactory.decodeStream(inputStream)
336                 }
337             }
338             if (inputStream == null)
339             {
340                 Log.w(TAG, "http: ($requestMethod) Response Code Error: $responseCode: $url")
341                 return (null)
342             }
343             inputStream.close()
344         }
345         catch (e: Exception)
346         {
347             Log.w(TAG, "http: (" + requestMethod + ") " + url + "  " + e.message)
348             e.printStackTrace()
349             return (null)
350         }
351         return (bmp)
352     }
353
354     /**
355      *
356      *
357      *
358      */
359     fun httpPost(url: String, postData: String?, timeoutMs: Int): String?
360     {
361         return (httpCommand(url, "POST", postData, null, null, timeoutMs))
362     }
363
364     /**
365      *
366      *
367      *
368      */
369     fun httpGetWithHeader(url: String, headerMap: Map<String, String>?, contentType: String?, timeoutMs: Int): String?
370     {
371         return (httpCommand(url, "GET", null, headerMap, contentType, timeoutMs))
372     }
373
374     /**
375      *
376      *
377      *
378      */
379     fun httpPostWithHeader(url: String, postData: String?, headerMap: Map<String, String>?, contentType: String?, timeoutMs: Int): String?
380     {
381         return (httpCommand(url, "POST", postData, headerMap, contentType, timeoutMs))
382     }
383
384     /**
385      *
386      *
387      *
388      */
389     fun httpPutWithHeader(url: String, putData: String?, headerMap: Map<String, String>?, contentType: String?, timeoutMs: Int): String?
390     {
391         return (httpCommand(url, "PUT", putData, headerMap, contentType, timeoutMs))
392     }
393
394     /**
395      *
396      *
397      *
398      */
399     fun httpPut(url: String, postData: String?, timeoutMs: Int): String?
400     {
401         return (httpCommand(url, "PUT", postData, null, null, timeoutMs))
402     }
403
404     /**
405      *
406      *
407      *
408      */
409     fun httpOptions(url: String, optionsData: String?, timeoutMs: Int): String?
410     {
411         return (httpCommand(url, "OPTIONS", optionsData, null, null, timeoutMs))
412     }
413
414     /**
415      *
416      *
417      *
418      */
419     private fun httpCommand(url: String, requestMethod: String, postData: String?, setProperty: Map<String, String>?, contentType: String?, timeoutMs: Int): String?
420     {
421         var inputStream: InputStream? = null
422         var timeout = timeoutMs
423         if (timeoutMs < 0)
424         {
425             timeout = DEFAULT_TIMEOUT
426         }
427
428         //  HTTP メソッドで要求を送出
429         try
430         {
431             val httpConn = URL(url).openConnection() as HttpURLConnection
432             httpConn.requestMethod = requestMethod
433             if (setProperty != null)
434             {
435                 for (key in setProperty.keys)
436                 {
437                     val value = setProperty[key]
438                     httpConn.setRequestProperty(key, value)
439                 }
440             }
441             if (contentType != null)
442             {
443                 httpConn.setRequestProperty("Content-Type", contentType)
444             }
445             httpConn.connectTimeout = timeout
446             httpConn.readTimeout = timeout
447             if (postData == null)
448             {
449                 httpConn.connect()
450             }
451             else
452             {
453                 httpConn.doInput = true
454                 httpConn.doOutput = true
455                 val outputStream = httpConn.outputStream
456                 val writer = OutputStreamWriter(outputStream, "UTF-8")
457                 writer.write(postData)
458                 writer.flush()
459                 writer.close()
460                 outputStream.close()
461             }
462             val responseCode = httpConn.responseCode
463             if (responseCode == HttpURLConnection.HTTP_OK)
464             {
465                 inputStream = httpConn.inputStream
466             }
467             if (inputStream == null)
468             {
469                 Log.w(TAG, "http $requestMethod : Response Code Error: $responseCode: $url")
470                 return ""
471             }
472         }
473         catch (e: Exception)
474         {
475             Log.w(TAG, "http " + requestMethod + " : IOException: " + e.message)
476             e.printStackTrace()
477             return ("")
478         }
479
480         // 応答の読み出し
481         return readFromInputStream(inputStream)
482     }
483
484     private fun readFromInputStream(inputStream: InputStream?): String
485     {
486         //var reader: BufferedReader? = null
487         var replyString = ""
488         if (inputStream == null)
489         {
490             return ""
491         }
492         try
493         {
494             val responseBuf = StringBuilder()
495             val reader = BufferedReader(InputStreamReader(inputStream))
496             var c: Int
497             while (reader.read().also { c = it } != -1)
498             {
499                 responseBuf.append(c.toChar())
500             }
501             replyString = responseBuf.toString()
502             reader.close()
503         }
504         catch (e: Exception)
505         {
506             e.printStackTrace()
507         }
508         return replyString
509     }
510
511     interface IReceivedMessageCallback
512     {
513         fun onCompleted()
514         fun onErrorOccurred(e: Exception?)
515         fun onReceive(readBytes: Int, length: Int, size: Int, data: ByteArray?)
516     }
517
518     companion object
519     {
520         private val TAG = SimpleHttpClient::class.java.simpleName
521         private const val DEFAULT_TIMEOUT = 10 * 1000 // [ms]
522         private const val BUFFER_SIZE = 131072 * 2 // 256kB
523     }
524 }