OSDN Git Service

Theta V に対応させる。
[gokigen/PKRemote.git] / app / src / main / java / net / osdn / gokigen / pkremote / camera / utils / SimpleHttpClient.java
1 package net.osdn.gokigen.pkremote.camera.utils;
2
3 import android.graphics.Bitmap;
4 import android.graphics.BitmapFactory;
5 import android.util.Log;
6
7 import java.io.BufferedReader;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.InputStreamReader;
11 import java.io.OutputStream;
12 import java.io.OutputStreamWriter;
13 import java.net.HttpURLConnection;
14 import java.net.URL;
15 import java.util.List;
16 import java.util.Map;
17
18 import androidx.annotation.NonNull;
19 import androidx.annotation.Nullable;
20
21 /**
22  *
23  *
24  *
25  */
26 public class SimpleHttpClient
27 {
28     private static final String TAG = SimpleHttpClient.class.getSimpleName();
29     private static final int DEFAULT_TIMEOUT = 10 * 1000; // [ms]
30     private static final int BUFFER_SIZE = 131072 * 2; // 256kB
31
32     public SimpleHttpClient()
33     {
34         Log.v(TAG, "SimpleHttpClient()");
35     }
36
37     /**
38      *
39      *
40      *
41      */
42     public static String httpGet(String url, int timeoutMs)
43     {
44         HttpURLConnection httpConn = null;
45         InputStream inputStream = null;
46         String replyString = "";
47
48         int timeout = timeoutMs;
49         if (timeoutMs < 0)
50         {
51             timeout = DEFAULT_TIMEOUT;
52         }
53
54         //  HTTP GETメソッドで要求を投げる
55         try
56         {
57             final URL urlObj = new URL(url);
58             httpConn = (HttpURLConnection) urlObj.openConnection();
59             httpConn.setRequestMethod("GET");
60             httpConn.setConnectTimeout(timeout);
61             httpConn.setReadTimeout(timeout);
62             httpConn.connect();
63
64             int responseCode = httpConn.getResponseCode();
65             if (responseCode == HttpURLConnection.HTTP_OK)
66             {
67                 inputStream = httpConn.getInputStream();
68             }
69             if (inputStream == null)
70             {
71                 Log.w(TAG, "httpGet: Response Code Error: " + responseCode + ": " + url);
72                 return ("");
73             }
74         }
75         catch (Exception e)
76         {
77             Log.w(TAG, "httpGet: " + url + "  " + e.getMessage());
78             e.printStackTrace();
79             if (httpConn != null)
80             {
81                 httpConn.disconnect();
82             }
83             return ("");
84         }
85
86         // 応答を確認する
87         BufferedReader reader = null;
88         try
89         {
90             StringBuilder responseBuf = new StringBuilder();
91             reader = new BufferedReader(new InputStreamReader(inputStream));
92             int c;
93             while ((c = reader.read()) != -1)
94             {
95                 responseBuf.append((char) c);
96             }
97             replyString = responseBuf.toString();
98         }
99         catch (Exception e)
100         {
101             Log.w(TAG, "httpGet: exception: " + e.getMessage());
102             e.printStackTrace();
103         }
104         finally
105         {
106             try
107             {
108                 if (reader != null)
109                 {
110                     reader.close();
111                 }
112             }
113             catch (Exception e)
114             {
115                 e.printStackTrace();
116             }
117             try
118             {
119                 inputStream.close();
120             }
121             catch (Exception e)
122             {
123                 e.printStackTrace();
124             }
125         }
126         return (replyString);
127     }
128
129     /**
130      *
131      *
132      *
133      */
134     public static void httpGetBytes(String url, Map<String, String> setProperty, int timeoutMs, @NonNull IReceivedMessageCallback callback)
135     {
136         httpCommandBytes(url, "GET", null, setProperty, null, timeoutMs, callback);
137     }
138
139     /**
140      *
141      *
142      *
143      */
144     public static void httpPostBytes(String url, String postData, Map<String, String> setProperty, int timeoutMs, @NonNull IReceivedMessageCallback callback)
145     {
146         httpCommandBytes(url, "POST", postData, setProperty, null, timeoutMs, callback);
147     }
148
149     /**
150      *
151      *
152      *
153      */
154     public static void httpPostBytesWithHeader(String url, String postData, Map<String, String> setProperty, @Nullable String contentType, int timeoutMs, @NonNull IReceivedMessageCallback callback)
155     {
156         httpCommandBytes(url, "POST", postData, setProperty, contentType, timeoutMs, callback);
157     }
158
159     private static void httpCommandBytes(@NonNull String url, @NonNull String requestMethod, @Nullable String postData, @Nullable Map<String, String> setProperty, @Nullable String contentType, int timeoutMs, @NonNull IReceivedMessageCallback callback)
160     {
161         HttpURLConnection httpConn = null;
162         OutputStream outputStream = null;
163         OutputStreamWriter writer = null;
164         InputStream inputStream = null;
165         int timeout = timeoutMs;
166         if (timeoutMs < 0)
167         {
168             timeout = DEFAULT_TIMEOUT;
169         }
170
171         //  HTTP メソッドで要求を送出
172         try
173         {
174             final URL urlObj = new URL(url);
175             httpConn = (HttpURLConnection) urlObj.openConnection();
176             httpConn.setRequestMethod(requestMethod);
177             if (setProperty != null)
178             {
179                 for (String key : setProperty.keySet())
180                 {
181                     String value = setProperty.get(key);
182                     httpConn.setRequestProperty(key, value);
183                 }
184             }
185             if (contentType != null)
186             {
187                 httpConn.setRequestProperty("Content-Type", contentType);
188             }
189             httpConn.setConnectTimeout(timeout);
190             httpConn.setReadTimeout(timeout);
191             if (postData == null)
192             {
193                 httpConn.connect();
194             }
195             else
196             {
197                 httpConn.setDoInput(true);
198                 httpConn.setDoOutput(true);
199                 outputStream = httpConn.getOutputStream();
200                 writer = new OutputStreamWriter(outputStream, "UTF-8");
201                 writer.write(postData);
202                 writer.flush();
203                 writer.close();
204                 writer = null;
205                 outputStream.close();
206                 outputStream = null;
207             }
208
209             int responseCode = httpConn.getResponseCode();
210             if (responseCode == HttpURLConnection.HTTP_OK)
211             {
212                 inputStream = httpConn.getInputStream();
213             }
214             if (inputStream == null)
215             {
216                 Log.w(TAG, " http " + requestMethod + " Response Code Error: " + responseCode + ": " + url);
217                 callback.onErrorOccurred(new NullPointerException());
218                 callback.onCompleted();
219                 return;
220             }
221         }
222         catch (Exception e)
223         {
224             Log.w(TAG, "http " + requestMethod + " " + url + "  " + e.getMessage());
225             e.printStackTrace();
226             if (httpConn != null)
227             {
228                 httpConn.disconnect();
229             }
230             callback.onErrorOccurred(e);
231             callback.onCompleted();
232             return;
233         }
234         finally
235         {
236             try
237             {
238                 if (writer != null)
239                 {
240                     writer.close();
241                 }
242             }
243             catch (Exception e)
244             {
245                 e.printStackTrace();
246             }
247             try
248             {
249                 if (outputStream != null)
250                 {
251                     outputStream.close();
252                 }
253             }
254             catch (IOException e)
255             {
256                 e.printStackTrace();
257             }
258         }
259
260         // 応答を確認する
261         try
262         {
263             int contentLength = httpConn.getContentLength();
264             if (contentLength < 0)
265             {
266                 // コンテンツ長が取れない場合の処理...
267                 try
268                 {
269                     Map<String, List<String>> headers = httpConn.getHeaderFields();
270
271                     /*
272                     // 応答ヘッダをすべてダンプするロジック...
273                     for (String key : headers.keySet())
274                     {
275                         final List<String> valueList = headers.get(key);
276                         Log.v(TAG, " " + key + " : " + getValue(valueList));
277                     }
278                     */
279
280                     // コンテンツ長さが取れない場合は、HTTP応答ヘッダから取得する
281                     List<String> valueList = headers.get("X-FILE_SIZE");
282                     try
283                     {
284                         if (valueList != null)
285                         {
286                             contentLength = Integer.parseInt(getValue(valueList));
287                         }
288                     }
289                     catch (Exception ee)
290                     {
291                         ee.printStackTrace();
292                     }
293                 }
294                 catch (Exception e)
295                 {
296                     e.printStackTrace();
297                 }
298             }
299
300             byte[] buffer = new byte[BUFFER_SIZE];
301             int readBytes = 0;
302             int readSize = inputStream.read(buffer, 0, BUFFER_SIZE);
303             while (readSize != -1)
304             {
305                 callback.onReceive(readBytes, contentLength, readSize, buffer);
306                 readBytes += readSize;
307                 readSize = inputStream.read(buffer, 0, BUFFER_SIZE);
308             }
309             Log.v(TAG, "RECEIVED " + readBytes + " BYTES. (contentLength : " + contentLength + ")");
310             inputStream.close();
311         }
312         catch (Exception e)
313         {
314             Log.w(TAG, "httpGet: exception: " + e.getMessage());
315             e.printStackTrace();
316             callback.onErrorOccurred(e);
317         }
318         finally
319         {
320             try
321             {
322                 inputStream.close();
323             }
324             catch (Exception e)
325             {
326                 e.printStackTrace();
327             }
328         }
329         callback.onCompleted();
330     }
331
332
333     public static String getValue(List<String> valueList)
334     {
335         // 応答ヘッダの値切り出し用...
336         boolean isFirst = true;
337         final StringBuilder values = new StringBuilder();
338         for (String value : valueList)
339         {
340             values.append(value);
341             if (isFirst)
342             {
343                 isFirst = false;
344             }
345             else
346             {
347                 values.append(" ");
348             }
349         }
350         return (values.toString());
351     }
352
353     public static Bitmap httpGetBitmap(String url, Map<String, String> setProperty, int timeoutMs)
354     {
355         return (httpCommandBitmap(url, "GET", null, setProperty, null, timeoutMs));
356     }
357
358     /**
359      *
360      *
361      *
362      */
363     public static Bitmap httpPostBitmap(String url, String postData, int timeoutMs)
364     {
365         return (httpCommandBitmap(url, "POST", postData, null, null, timeoutMs));
366     }
367
368     /**
369      *
370      *
371      *
372      */
373     public static Bitmap httpPostBitmapWithHeader(String url, String postData, @Nullable Map<String, String> setProperty, @Nullable String contentType, int timeoutMs)
374     {
375         return (httpCommandBitmap(url, "POST", postData, setProperty, contentType, timeoutMs));
376     }
377
378     /**
379      *
380      *
381      *
382      */
383     private static Bitmap httpCommandBitmap(@NonNull String url, @NonNull String requestMethod, @Nullable String postData, @Nullable Map<String, String> setProperty, @Nullable String contentType, int timeoutMs)
384     {
385         HttpURLConnection httpConn = null;
386         InputStream inputStream = null;
387         OutputStream outputStream = null;
388         OutputStreamWriter writer = null;
389         Bitmap bmp = null;
390
391         int timeout = timeoutMs;
392         if (timeoutMs < 0)
393         {
394             timeout = DEFAULT_TIMEOUT;
395         }
396
397         //  HTTP メソッドで要求を送出
398         try
399         {
400             final URL urlObj = new URL(url);
401             httpConn = (HttpURLConnection) urlObj.openConnection();
402             httpConn.setRequestMethod(requestMethod);
403             if (setProperty != null)
404             {
405                 for (String key : setProperty.keySet())
406                 {
407                     String value = setProperty.get(key);
408                     httpConn.setRequestProperty(key, value);
409                 }
410             }
411             if (contentType != null)
412             {
413                 httpConn.setRequestProperty("Content-Type", contentType);
414             }
415             httpConn.setConnectTimeout(timeout);
416             httpConn.setReadTimeout(timeout);
417
418             if (postData == null)
419             {
420                 httpConn.connect();
421             }
422             else
423             {
424                 httpConn.setDoInput(true);
425                 httpConn.setDoOutput(true);
426                 outputStream = httpConn.getOutputStream();
427                 writer = new OutputStreamWriter(outputStream, "UTF-8");
428                 writer.write(postData);
429                 writer.flush();
430                 writer.close();
431                 writer = null;
432                 outputStream.close();
433                 outputStream = null;
434             }
435
436             int responseCode = httpConn.getResponseCode();
437             if (responseCode == HttpURLConnection.HTTP_OK)
438             {
439                 inputStream = httpConn.getInputStream();
440                 if (inputStream != null)
441                 {
442                     bmp = BitmapFactory.decodeStream(inputStream);
443                 }
444             }
445             if (inputStream == null)
446             {
447                 Log.w(TAG, "http: (" + requestMethod + ") Response Code Error: " + responseCode + ": " + url);
448                 return (null);
449             }
450             inputStream.close();
451         }
452         catch (Exception e)
453         {
454             Log.w(TAG, "http: (" + requestMethod + ") " + url + "  " + e.getMessage());
455             e.printStackTrace();
456             if (httpConn != null)
457             {
458                 httpConn.disconnect();
459             }
460             return (null);
461         }
462         finally
463         {
464             try
465             {
466                 if (writer != null)
467                 {
468                     writer.close();
469                 }
470             }
471             catch (Exception e)
472             {
473                 e.printStackTrace();
474             }
475             try
476             {
477                 if (outputStream != null)
478                 {
479                     outputStream.close();
480                 }
481             }
482             catch (IOException e)
483             {
484                 e.printStackTrace();
485             }
486         }
487         return (bmp);
488     }
489
490     /**
491      *
492      *
493      *
494      */
495     public static String httpPost(String url, String postData, int timeoutMs)
496     {
497         return (httpCommand(url, "POST", postData, null, null, timeoutMs));
498     }
499
500     /**
501      *
502      *
503      *
504      */
505     public static String httpGetWithHeader(String url, Map<String, String> headerMap, String contentType, int timeoutMs)
506     {
507         return (httpCommand(url, "GET", null, headerMap, contentType, timeoutMs));
508     }
509
510     /**
511      *
512      *
513      *
514      */
515     public static String httpPostWithHeader(String url, String postData, Map<String, String> headerMap, String contentType, int timeoutMs)
516     {
517         return (httpCommand(url, "POST", postData, headerMap, contentType, timeoutMs));
518     }
519
520     /**
521      *
522      *
523      *
524      */
525     public static String httpPutWithHeader(String url, String putData, Map<String, String> headerMap, String contentType, int timeoutMs)
526     {
527         return (httpCommand(url, "PUT", putData, headerMap, contentType, timeoutMs));
528     }
529
530     /**
531      *
532      *
533      *
534      */
535     public static String httpPut(String url, String postData, int timeoutMs)
536     {
537         return (httpCommand(url, "PUT", postData, null, null, timeoutMs));
538     }
539
540     /**
541      *
542      *
543      *
544      */
545     public static String httpOptions(String url, String optionsData, int timeoutMs)
546     {
547         return (httpCommand(url, "OPTIONS", optionsData, null, null, timeoutMs));
548     }
549
550     /**
551      *
552      *
553      *
554      */
555     private static String httpCommand(String url, String requestMethod, String postData, Map<String, String> setProperty, String contentType, int timeoutMs)
556     {
557         HttpURLConnection httpConn = null;
558         OutputStream outputStream = null;
559         OutputStreamWriter writer = null;
560         InputStream inputStream = null;
561
562         int timeout = timeoutMs;
563         if (timeoutMs < 0)
564         {
565             timeout = DEFAULT_TIMEOUT;
566         }
567
568         //  HTTP メソッドで要求を送出
569         try
570         {
571             final URL urlObj = new URL(url);
572             httpConn = (HttpURLConnection) urlObj.openConnection();
573             httpConn.setRequestMethod(requestMethod);
574             if (setProperty != null)
575             {
576                 for (String key : setProperty.keySet())
577                 {
578                     String value = setProperty.get(key);
579                     httpConn.setRequestProperty(key, value);
580                 }
581             }
582             if (contentType != null)
583             {
584                 httpConn.setRequestProperty("Content-Type", contentType);
585             }
586             httpConn.setConnectTimeout(timeout);
587             httpConn.setReadTimeout(timeout);
588
589             if (postData == null)
590             {
591                 httpConn.connect();
592             }
593             else
594             {
595                 httpConn.setDoInput(true);
596                 httpConn.setDoOutput(true);
597                 outputStream = httpConn.getOutputStream();
598                 writer = new OutputStreamWriter(outputStream, "UTF-8");
599                 writer.write(postData);
600                 writer.flush();
601                 writer.close();
602                 writer = null;
603                 outputStream.close();
604                 outputStream = null;
605             }
606             int responseCode = httpConn.getResponseCode();
607             if (responseCode == HttpURLConnection.HTTP_OK)
608             {
609                 inputStream = httpConn.getInputStream();
610             }
611             if (inputStream == null)
612             {
613                 Log.w(TAG, "http " + requestMethod + " : Response Code Error: " + responseCode + ": " + url);
614 /*
615                 inputStream = httpConn.getInputStream();
616                 if (inputStream != null)
617                 {
618                     // DUMP RESPONSE DETAIL
619                     Log.w(TAG, " RESP : " + readFromInputStream(inputStream));
620                 }
621 */
622                 return ("");
623             }
624         }
625         catch (Exception e)
626         {
627             Log.w(TAG, "http " + requestMethod + " : IOException: " + e.getMessage());
628             e.printStackTrace();
629             if (httpConn != null)
630             {
631                 httpConn.disconnect();
632             }
633             return ("");
634         }
635         finally
636         {
637             try
638             {
639                 if (writer != null)
640                 {
641                     writer.close();
642                 }
643             }
644             catch (Exception e)
645             {
646                 e.printStackTrace();
647             }
648             try
649             {
650                 if (outputStream != null)
651                 {
652                     outputStream.close();
653                 }
654             }
655             catch (IOException e)
656             {
657                 e.printStackTrace();
658             }
659         }
660
661         // 応答の読み出し
662         return (readFromInputStream(inputStream));
663 /*
664         BufferedReader reader = null;
665         String replyString = "";
666         try
667         {
668             StringBuilder responseBuf = new StringBuilder();
669             reader = new BufferedReader(new InputStreamReader(inputStream));
670
671             int c;
672             while ((c = reader.read()) != -1)
673             {
674                 responseBuf.append((char) c);
675             }
676             replyString = responseBuf.toString();
677         }
678         catch (Exception e)
679         {
680             e.printStackTrace();
681         }
682         finally
683         {
684             try
685             {
686                 if (reader != null)
687                 {
688                     reader.close();
689                 }
690             }
691             catch (IOException e)
692             {
693                 e.printStackTrace();
694             }
695         }
696         return (replyString);
697 */
698     }
699
700     private static String readFromInputStream(InputStream inputStream)
701     {
702         BufferedReader reader = null;
703         String replyString = "";
704         if (inputStream == null)
705         {
706             return ("");
707         }
708         try
709         {
710             StringBuilder responseBuf = new StringBuilder();
711             reader = new BufferedReader(new InputStreamReader(inputStream));
712
713             int c;
714             while ((c = reader.read()) != -1)
715             {
716                 responseBuf.append((char) c);
717             }
718             replyString = responseBuf.toString();
719         }
720         catch (Exception e)
721         {
722             e.printStackTrace();
723         }
724         finally
725         {
726             try
727             {
728                 if (reader != null)
729                 {
730                     reader.close();
731                 }
732             }
733             catch (IOException e)
734             {
735                 e.printStackTrace();
736             }
737         }
738         return (replyString);
739     }
740
741
742     public interface IReceivedMessageCallback
743     {
744         void onCompleted();
745         void onErrorOccurred(Exception  e);
746         void onReceive(int readBytes, int length, int size, byte[] data);
747     }
748 }