001    /*
002     * Copyright (c) 2009 The openGion Project.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
013     * either express or implied. See the License for the specific language
014     * governing permissions and limitations under the License.
015     */
016    package org.opengion.fukurou.util;
017    
018    import java.io.BufferedInputStream;
019    import java.io.BufferedReader;
020    import java.io.File;
021    import java.io.IOException;
022    import java.io.InputStream;
023    import java.io.InputStreamReader;
024    import java.io.OutputStream;
025    import java.io.PrintStream;
026    import java.io.PrintWriter;
027    import java.io.UnsupportedEncodingException;
028    import java.net.HttpURLConnection;
029    import java.net.InetSocketAddress;
030    import java.net.Proxy;
031    import java.net.SocketAddress;
032    import java.net.URL;
033    import java.net.URLConnection;
034    
035    import org.apache.commons.codec.binary.Base64;
036    
037    /**
038     * URLConnect は、指定ã?URL にアクセスして、情報/ãƒ??タを取得しますã?
039     * URL へのアクセスにより、エンジンではå�?¨®処ç�?‚’実行させることが可能になりますã?
040     * 例えば、帳票ãƒ??モンの起動やã€?•·時間かかるå?ç�??実行などですã?
041     * なおã?URLに引数が付く場合ã?、ダブルコーãƒ??ションで括って下さã�??
042     * - 付き引数は、指定é?番はã€?–¢係ありませんã€? 無し引数(url,user:passwd)はã€?
043     * é ?•ªがありますã?
044     *
045     * Usage: java org.opengion.fukurou.util.URLConnect [-info/-data] … url [user:passwd]
046     *
047     *   args[*] : [-info/-data]       æƒ??の取得か、データの取得かを指定しまã�?初期値:-data)ã€?
048     *   args[*] : [-post=ファイル名]  POSTメソãƒ?ƒ‰を指定して、ファイルãƒ??タをé?信しまã�?初期値:-get)ã€?
049     *   args[*] : [-encode=UTF-8]     エンコードをæŒ?®šしまã�?通常は接続å?のencodeを使用)ã€?
050     *   args[*] : [-out=ファイル名]   結果を指定されたファイルエンコードでファイルに出力しますã?
051     *   args[*] : [-errEx=true/false] trueの場合ã??šス?Ž゚ンス?º?°??¾žがã€?XX,5XX の時に RuntimeException を投げまã�?初期値:false)ã€?
052     *   args[A] : url                 ?µ?²?¬を指定しますã?GETの場合ã?パラメータは ?KEY=VALですã?
053     *   args[B] : [user:passwd]       BASIC認証のエリアへのアクセス時にæŒ?®šしますã?
054     *
055     * ※ プロキシ設定ã??“つの方æ³?
056     * プロキシ設定にはã€?¼“つの方法がありますã?
057     *   1.
058     *     URL url = URL( "http",proxyHost,proxyPort, url );
059     *     URLConnection urlConn = url.openConnection();
060     *   2.
061     *     SocketAddress scaddr = new InetSocketAddress( proxyHost, proxyPort );
062     *     Proxy proxy = new Proxy( Proxy.Type.HTTP, scaddr );
063     *     URL url = new Url( url );
064     *     URLConnection urlConn = url.openConnection( proxy );
065     *   3.
066     *     System.setProperty( "http.proxyHost",host );
067     *     System.setProperty( "http.proxyPort",String.valueOf( port ) );
068     *     URL url = new Url( url );
069     *     URLConnection urlConn = url.openConnection();
070     *     System.clearProperty( "http.proxyHost" );
071     *     System.clearProperty( "http.proxyPort" );
072     *
073     * 1. ã€?. の方法ã?、urlConn.getContentType() を実行すると、エラーになりますã?(原因不æ?)
074     * 3. の方法では、ã?ルチスレãƒ?ƒ‰で実行するå?合に、問題が発生しますã?
075     * 本クラスでは、方法ï¼?を使用してã�?�¾すã?
076     *
077     * @version  4.0
078     * @author   Kazuhiko Hasegawa
079     * @since    JDK5.0,
080     */
081    public class URLConnect {
082            private static final String CR = System.getProperty("line.separator");
083    
084    //      private static final String     ENCODE  = "UTF-8";
085    
086            private final String urlStr ;
087            private final String userPass ;
088    
089            private int                             rpsCode         = -1;
090            private String                  rpsMethod       = null;
091            private String                  rpsMessage      = null;
092            private String                  type            = null;
093            private String                  charset         = null;
094            private String                  postData        = null;
095            private long                    length          = -1;
096            private long                    date            = -1;
097            private long                    modified        = -1;
098            private boolean                 isPost          = false;
099            private URLConnection   conn            = null;
100            private Proxy                   proxy           = Proxy.NO_PROXY;
101            
102            // 5.8.3.0 (2015/01/09) 追åŠ?
103            private String[]                propKeys;
104            private String[]                propVals;
105    
106            /**
107             * コンストラクター
108             *
109             * @param       url     接続するアドレスを指定しますã?(http://server:port/dir/file.html)
110             * @param       pass    ユーザー?šパスワーãƒ?認証接続がå¿?¦�な場å�?
111             */
112            public URLConnect( final String url, final String pass ) {
113                    urlStr = url;
114                    userPass = pass;
115            }
116    
117            /**
118             * æŒ?®šã?URLに対して、コネクトするã?に使用するプロキシ設定を行いますã?
119             * こã?ときに、ã?ãƒ?ƒ€ーæƒ??をå?部変数に設定しておきますã?
120             *
121             * @param       host    接続するã?ロキシのホスト名
122             * @param       port    接続するã?ロキシのポã?ト番号
123             */
124            public void setProxy( final String host,final int port ) {
125                    // 方æ³?.
126                    SocketAddress scaddr = new InetSocketAddress( host, port );
127                    proxy = new Proxy( Proxy.Type.HTTP, scaddr );
128            }
129    
130            /**
131             * æŒ?®šã?URLに対して、コネクトしますã?
132             * こã?ときに、ã?ãƒ?ƒ€ーæƒ??をå?部変数に設定しておきますã?
133             *
134             * @og.rev 4.0.1.0 (2007/12/12) Postでè¤?•°キーを使えるように修正
135             * @og.rev 5.1.6.0 (2010/05/01) charsetを指定できるようにする
136             * @throws  IOException 入出力エラーが発生したとã�?
137             */
138            public void connect() throws IOException {
139                    conn = getConnection();
140    
141                    if( isPost ) {
142                            conn.setDoOutput( true );                       // POST可能にする
143    
144                            OutputStream os = null;                         // POST用のOutputStream
145                            PrintStream  ps = null;
146                            try {
147                                    os = conn.getOutputStream();    // POST用のOutputStreamを取å¾?
148                                    // 5.1.6.0 (2010/05/01)
149                                    if( charset != null ) {
150                                            ps = new PrintStream( os, false, charset );
151                                    }
152                                    else {
153                                            ps = new PrintStream( os );
154                                    }
155                                    ps.print( postData );                   // 4.1.0.0 (2007/12/22)
156                            }
157                            finally {
158                                    Closer.ioClose( ps );           // close 処ç�?™‚の IOException を無è¦?
159                                    Closer.ioClose( os );           // close 処ç�?™‚の IOException を無è¦?
160                            }
161                    }
162                    else {
163                            // GET 時ã?コネクション接ç¶?
164                            conn.connect();
165                    }
166    
167                    setInfo( conn );
168            }
169    
170            /**
171             * U接続å?のãƒ??タを取得しますã?
172             *
173             * こã?処ç�??前に、connect() 処ç�?‚’実行しておくå¿?¦�がありますã?
174             * 取得したデータは、指定ã?URL へのアクセスのみですã?
175             * 通常のWebブラウザは、イメージã‚??JavaScriptファイル、CSSファイルなどã€?
176             * å�?¨®ファイル毎にHTTP接続を行い、取得して、レンãƒ?ƒªングしますã?
177             * こã?メソãƒ?ƒ‰での処ç�?�§は、それらのファイルå†?�«æŒ?®šされてã�?‚‹URLの
178             * 再帰çš?�ª取得ã?行いませんã€?
179             * よって、フレーãƒ??ç�?�ªども行いませんã€?
180             * 本来は、Stream のまま処ç�?�™ることで、バイナリãƒ??タも扱えますが、ここではã€?
181             * ãƒ?‚­ストデータ(String)に変換して使用できるãƒ??タのみ扱えますã?
182             *
183             * @return      接続結果
184             * @throws  IOException 入出力エラーが発生したとã�?
185             */
186            public String readData() throws IOException {
187                    if( conn == null ) {
188                            String errMsg = "connect() されてã�?�¾せん。データ取得前にconnect()してくださいã€?;
189                            throw new RuntimeException( errMsg );
190                    }
191    
192                    BufferedReader reader = null;
193                    StringBuilder buf = new StringBuilder();
194                    try {
195                            reader = getReader();
196    
197                            String line ;
198                            while( (line = reader.readLine()) != null ) {
199                                    buf.append( line ).append( CR );
200                            }
201                    }
202                    catch( UnsupportedEncodingException ex ) {
203                            String errMsg = "æŒ?®šされたæ–?­—エンコーãƒ?‚£ングがサポã?トされてã�?�¾せんã€? + CR
204                                                    + " url=[" + urlStr + "]"
205                                                    + " charset=[" + charset + "]" ;
206                            throw new RuntimeException( errMsg,ex );
207                    }
208                    finally {
209                            Closer.ioClose( reader );
210                            disconnect();
211                    }
212    
213                    return buf.toString();
214            }
215    
216            /**
217             * サーバへのほかã?要求が今後発生しそうになã�?�“とを示しますã?
218             *
219             */
220            public void disconnect() {
221                    if( conn instanceof HttpURLConnection ) {
222                            ((HttpURLConnection)conn).disconnect() ;
223                    }
224            }
225    
226            /**
227             * URL と ユーザー?šパスワードを与えて、URLConnectionを返しますã?
228             *
229             * ユーザー?šパスワーãƒ?ã�?null でなã�??合ã?、BASCI認証エリアへのアクセスの為ã€?
230             * BASE64Encoder を行って、Authorization プロパティーを設定しますã?
231             * ここで返す URLConnection は、すでに、connect() メソãƒ?ƒ‰実行済みの
232             * リモート接続が完äº?�—た状態ã?オブジェクトですã?
233             * 
234             * @og.rev 5.8.3.0 (2015/01/09) 
235             *
236             * @return  URLConnectionオブジェクãƒ?
237             * @throws  IOException 入出力エラーが発生したとã�?
238             */
239            // 5.1.5.0 (2010/04/01) SOAP対応により、PROTECTEDåŒ?
240            protected URLConnection getConnection() throws IOException {
241    //      private URLConnection getConnection() throws IOException {
242                    final URL url = new URL( urlStr );
243    
244                    // 方æ³?.
245                    URLConnection urlConn = url.openConnection( proxy );
246    
247                    if( userPass != null ) {
248    //                      byte[] encoded = Base64.encodeBase64( userPass.getBytes() );
249    //                      String userPassEnc = new String( encoded );
250                            byte[] encoded = Base64.encodeBase64( userPass.getBytes( StringUtil.DEFAULT_CHARSET ) );        // 5.5.2.6 (2012/05/25) findbugs対å¿?
251                            String userPassEnc = new String( encoded,StringUtil.DEFAULT_CHARSET );          // 5.5.2.6 (2012/05/25) findbugs対å¿?
252                            urlConn.setRequestProperty( "Authorization","Basic " + userPassEnc );
253                    }
254                    
255                    // 5.8.3.0 (2015/01/09) RequestPropertyのセãƒ?ƒˆ
256                    if( propKeys != null && propKeys.length > 0 ){
257                            for(int i = 0; i < propKeys.length; i++){
258                                    urlConn.setRequestProperty( propKeys[i], propVals[i] );
259                            }
260                    }
261    
262                    return urlConn ;
263            }
264    
265            /**
266             * 接続å?のæƒ??をå?部変数に設定しますã?
267             *
268             * ここでは、タイãƒ?エンコーãƒ?レスポンスコーãƒ?レスポンスメãƒ?‚»ージ を設定しますã?
269             * レスポンスコーãƒ?レスポンスメãƒ?‚»ージは、接続コネクションがã?HttpURLConnection の
270             * 場合ã?みセãƒ?ƒˆされますã?
271             * 途中でエラーが発生したå?合でもã?継続å?ç�?�§きるようにしますã?これは、ã?ロキシ
272             * 設定ã?方法により、conn.getContentType()  でエラーが発生するå?合があるためですã?
273             *
274             * @og.rev 5.5.9.1 (2012/12/07) charsetは、null の場合ã?み設定しますã?
275             *
276             * @param   conn 接続å?のコネクション
277             */
278            private void setInfo( final URLConnection conn ) {
279                    try {
280                            // 5.5.9.1 (2012/12/07) charsetは、null の場合ã?み設定しますã?
281                            if( charset == null ) { charset = conn.getContentEncoding(); }
282                            type    = conn.getContentType() ;
283                            length  = conn.getContentLength();
284                            date    = conn.getDate();
285                            modified= conn.getLastModified();
286    
287                            if( charset == null && type != null ) {
288                                    int adrs = type.indexOf( "charset" );
289                                    int adrs2 = type.indexOf( '=',adrs );
290                                    if( adrs > 0 && adrs2 > adrs ) {
291                                            charset = type.substring( adrs2+1 ).trim();
292                                    }
293                            }
294    
295                            if( conn instanceof HttpURLConnection ) {
296                                    HttpURLConnection httpConn = (HttpURLConnection) conn;
297                                    rpsCode         = httpConn.getResponseCode();
298                                    rpsMethod       = httpConn.getRequestMethod();
299                                    rpsMessage      = httpConn.getResponseMessage() + code2Message( rpsCode );
300                            }
301                    }
302                    // 4.0.0.0 (2007/11/29) Exception から、IOException と RuntimeException に変更
303                    catch( IOException ex ) {
304                            System.out.println( ex.getMessage() );
305                    }
306                    catch( RuntimeException ex ) {
307                            System.out.println( ex.getMessage() );
308                    }
309            }
310    
311            /**
312             * URL æƒ??を取得しますã?
313             *
314             * @og.rev 4.3.4.4 (2009/01/01) メソãƒ?ƒ‰名変更
315             *
316             * @return      URL�?
317             */
318            public String getUrl() { return urlStr; }
319    
320            /**
321             * setRequestPropertyでセãƒ?ƒˆするãƒ??タを設定しますã?
322             *
323             * keys,valså�??、カンマ区åˆ?‚Šでåˆ?§£しますã?
324             *
325             * @og.rev 5.8.3.0 (2007/12/22) 追åŠ?
326             * @param       keys    パラメータキー?ˆカンマ区åˆ?‚Š??
327             * @param       vals    パラメータ?ˆカンマ区åˆ?‚Š??
328             */
329            public void setRequestProperty( final String keys, final String vals ) {
330                    if( keys != null && keys.length() > 0 && vals != null && vals.length() > 0 ){
331                            propKeys = StringUtil.csv2Array( keys );
332                            propVals = StringUtil.csv2Array( vals );
333    
334                            if( propKeys.length != propVals.length ) {
335                                    final String errMsg = "パラメータのキーと、å?の数がä¸??しませんã€?    + CR
336                                                            + " key=[" + keys + "]"                                                                 + CR
337                                                            + " val=[" + vals + "]" ;
338                                    throw new IllegalArgumentException( errMsg );
339                            }
340                    }
341            }
342            
343            /**
344             * POSTするãƒ??タを設定しますã?
345             *
346             * POSTする場合ã?、connect() 処ç�?‚’行う前に、データを設定しておくå¿?¦�がありますã?
347             *
348             * @og.rev 4.1.0.0 (2007/12/22) キーと値のセãƒ?ƒˆを取得するよã�?¤‰更
349             * @param       data    POSTãƒ??タ
350             */
351            public void setPostData( final String data ) {
352                    postData = data;
353                    if( postData != null && "?".indexOf( postData ) == 0 ) { // 先é?の?を抜ã�?
354                            postData = postData.substring(1);
355                    }
356                    if( postData != null ) { isPost = true; }
357            }
358    
359            /**
360             * タイãƒ?æƒ??を取得しますã?
361             *
362             * @return      タイãƒ?æƒ??
363             */
364            public String getType() { return type; }
365    
366            /**
367             * ãƒ??タé‡?æƒ??を取得しますã?
368             *
369             * @return      ãƒ??タé‡?æƒ??
370             */
371            public long getLength() { return length; }
372    
373            /**
374             * 作æ?日æ™?æƒ??を取得しますã?
375             *
376             * @return      作æ?日æ™?
377             */
378            public long getDate() { return date; }
379    
380            /**
381             * 更新日æ™?æƒ??を取得しますã?
382             *
383             * @return      更新日æ™?
384             */
385            public long getModified() { return modified; }
386    
387            /**
388             * 結果コーãƒ?æƒ??(HttpURLConnection)を取得しますã?
389             *
390             * @return      結果コーãƒ?æƒ??
391             */
392            public int getCode() { return rpsCode; }
393    
394            /**
395             * メソãƒ?ƒ‰ æƒ??(HttpURLConnection)を取得しますã?
396             *
397             * @return      メソãƒ?ƒ‰ æƒ??
398             */
399            public String getMethod() { return rpsMethod; }
400    
401            /**
402             * メãƒ?‚»ージ æƒ??(HttpURLConnection)を取得しますã?
403             *
404             * @return      メãƒ?‚»ージ æƒ??
405             */
406            public String getMessage() { return rpsMessage; }
407    
408            /**
409             * キャラクタ æƒ??を取得しますã?
410             *
411             * @return      キャラクタ æƒ??
412             */
413            public String getCharset() { return charset; }
414    
415            /**
416             * キャラクタ æƒ??を設定しますã?
417             *
418             * @param  chset キャラクタ æƒ??
419             */
420            public void setCharset( final String chset ) { charset = chset; }
421    
422            /**
423             * 接続å?のãƒ??タのリーãƒ??を取得しますã?
424             *
425             * こã?処ç�??前に、connect() 処ç�?‚’実行しておくå¿?¦�がありますã?
426             * 取得したデータは、指定ã?URL へのアクセスのみですã?
427             * 通常のWebブラウザは、イメージã‚??JavaScriptファイル、CSSファイルなどã€?
428             * å�?¨®ファイル毎にHTTP接続を行い、取得して、レンãƒ?ƒªングしますã?
429             * こã?メソãƒ?ƒ‰での処ç�?�§は、それらのファイルå†?�«æŒ?®šされてã�?‚‹URLの
430             * 再帰çš?�ª取得ã?行いませんã€?
431             * よって、フレーãƒ??ç�?�ªども行いませんã€?
432             *
433             * @return      接続結果のリーãƒ??
434             * @throws  IOException 入出力エラーが発生したとã�?
435             */
436            public BufferedReader getReader() throws IOException {
437                    InputStream in = conn.getInputStream();
438    
439                    final BufferedReader reader ;
440                    if( charset != null ) {
441                            reader = new BufferedReader( new InputStreamReader( in,charset ) );
442                    }
443                    else {
444    //                      reader = new BufferedReader( new InputStreamReader( in ) );
445                            reader = new BufferedReader( new InputStreamReader( in,StringUtil.DEFAULT_CHARSET ) );          // 5.5.2.6 (2012/05/25) findbugs対å¿?
446                    }
447    
448                    return reader;
449            }
450    
451            /**
452             * 接続å?のãƒ??タの入力ストリーãƒ?‚’取得しますã?
453             *
454             * こã?処ç�??前に、connect() 処ç�?‚’実行しておくå¿?¦�がありますã?
455             * 取得したデータは、指定ã?URL へのアクセスのみですã?
456             * 通常のWebブラウザは、イメージã‚??JavaScriptファイル、CSSファイルなどã€?
457             * å�?¨®ファイル毎にHTTP接続を行い、取得して、レンãƒ?ƒªングしますã?
458             * こã?メソãƒ?ƒ‰での処ç�?�§は、それらのファイルå†?�«æŒ?®šされてã�?‚‹URLの
459             * 再帰çš?�ª取得ã?行いませんã€?
460             * よって、フレーãƒ??ç�?�ªども行いませんã€?
461             *
462             * @og.rev 5.4.2.0 (2011/12/01) 新規追åŠ?
463             *
464             * @return      接続結果の入力を出力しますã?
465             * @throws  IOException 入出力エラーが発生したとã�?
466             */
467            public InputStream getInputStream() throws IOException {
468    //              InputStream in = new BufferedInputStream( conn.getInputStream() );
469    //              return in;
470                    return new BufferedInputStream( conn.getInputStream() );                // 5.5.2.4 (2012/05/16)
471            }
472    
473            /**
474             * HttpURLConnection のレスポンスコードに対応するメãƒ?‚»ージæ–?­—å?を返しますã?
475             *
476             * HttpURLConnection の getResponseCode() メソãƒ?ƒ‰により取得された、HTTPレスポンスコーãƒ?
477             * に対応する文字å?を返しますã?こã?æ–?­—å?は、HttpURLConnection で定義されã�?
478             * static 定数のコメントを、定義してã�?�¾すã?
479             *
480             * @og.rev 5.6.7.0 (2013/07/27) レスポンスコードä¾?追åŠ?
481             *
482             * @param       code    HTTPレスポンスコーãƒ?
483             *
484             * @return      レスポンスコードに対応する文字å?
485             * @see HttpURLConnection#HTTP_ACCEPTED
486             */
487            public static String code2Message( final int code ) {
488                    final String msg ;
489                    switch( code ) {
490                            case 100                                                                                : msg = "100: 要求ã?続行可能ですã?"                                                ;       break;  // 5.6.7.0 (2013/07/27)
491                            case 101                                                                                : msg = "101: プロトコルをå?り替えますã?"                             ;       break;  // 5.6.7.0 (2013/07/27)
492                            case HttpURLConnection.HTTP_OK                                  : msg = "200: OK ですã?"                                                         ;       break;
493                            case HttpURLConnection.HTTP_CREATED                     : msg = "201: 作æ?されましたã€?                                                     ;       break;
494                            case HttpURLConnection.HTTP_ACCEPTED                    : msg = "202: 許可されましたã€?                                                    ;       break;
495                            case HttpURLConnection.HTTP_NOT_AUTHORITATIVE   : msg = "203: 不当なæƒ??ですã?"                                                    ;       break;
496                            case HttpURLConnection.HTTP_NO_CONTENT                  : msg = "204: コンãƒ?ƒ³ãƒ?�Œありませんã€?                                      ;       break;
497                            case HttpURLConnection.HTTP_RESET                               : msg = "205: コンãƒ?ƒ³ãƒ?‚’リセãƒ?ƒˆしますã?"                          ;       break;
498                            case HttpURLConnection.HTTP_PARTIAL                     : msg = "206: 部åˆ?š„なコンãƒ?ƒ³ãƒ?�§すã?"                                     ;       break;
499                            case HttpURLConnection.HTTP_MULT_CHOICE                 : msg = "300: è¤?•°選択されてã�?�¾すã?"                                        ;       break;
500                            case HttpURLConnection.HTTP_MOVED_PERM                  : msg = "301: 永続的に移動されましたã€?                                      ;       break;
501                            case HttpURLConnection.HTTP_MOVED_TEMP                  : msg = "302: ä¸?™‚çš?�«åˆ?‚Š替えますã?"                                        ;       break;
502                            case HttpURLConnection.HTTP_SEE_OTHER                   : msg = "303: 他を参ç?してくださいã€?                                 ;       break;
503                            case HttpURLConnection.HTTP_NOT_MODIFIED                : msg = "304: 修正されませんでしたã€?                                       ;       break;
504                            case HttpURLConnection.HTTP_USE_PROXY                   : msg = "305: プロキシを使用してくださいã€?                          ;       break;
505                            case 306                                                                                : msg = "306: 仕様ã?拡張案ですã?"                                          ;       break;  // 5.6.7.0 (2013/07/27)
506                            case 307                                                                                : msg = "307: ä¸?™‚çš?�ªリãƒ?‚¤レクトですã?"                            ;       break;  // 5.6.7.0 (2013/07/27)
507                            case HttpURLConnection.HTTP_BAD_REQUEST                 : msg = "400: 不当な要求ですã?"                                                    ;       break;
508                            case HttpURLConnection.HTTP_UNAUTHORIZED                : msg = "401: 認証されませんでしたã€?                                       ;       break;
509                            case HttpURLConnection.HTTP_PAYMENT_REQUIRED    : msg = "402: 支払いがå¿?¦�ですã?"                                          ;       break;
510                            case HttpURLConnection.HTTP_FORBIDDEN                   : msg = "403: 禁止されてã�?�¾すã?"                                          ;       break;
511                            case HttpURLConnection.HTTP_NOT_FOUND                   : msg = "404: 見つかりませんでしたã€?                                        ;       break;
512                            case HttpURLConnection.HTTP_BAD_METHOD                  : msg = "405: メソãƒ?ƒ‰は許可されませんã€?                           ;       break;
513                            case HttpURLConnection.HTTP_NOT_ACCEPTABLE              : msg = "406: 許容されませんã€?                                                    ;       break;
514                            case HttpURLConnection.HTTP_PROXY_AUTH                  : msg = "407: プロキシの認証がå¿?¦�ですã?"                          ;       break;
515                            case HttpURLConnection.HTTP_CLIENT_TIMEOUT              : msg = "408: 要求が時間åˆ?‚Œですã?"                                         ;       break;
516                            case HttpURLConnection.HTTP_CONFLICT                    : msg = "409: 重è¤?�—てã�?�¾すã?"                                                    ;       break;
517                            case HttpURLConnection.HTTP_GONE                                : msg = "410: 存在しませんã€?                                                       ;       break;
518                            case HttpURLConnection.HTTP_LENGTH_REQUIRED     : msg = "411: 長さがå¿?¦�ですã?"                                                    ;       break;
519                            case HttpURLConnection.HTTP_PRECON_FAILED               : msg = "412: 前提条件が正しくありませんã€?                          ;       break;
520                            case HttpURLConnection.HTTP_ENTITY_TOO_LARGE    : msg = "413: 要求エンãƒ?‚£ãƒ?‚£が長すぎますã?"                 ;       break;
521                            case HttpURLConnection.HTTP_REQ_TOO_LONG                : msg = "414: 要æ±?URL が長すぎますã?"                                      ;       break;
522                            case HttpURLConnection.HTTP_UNSUPPORTED_TYPE    : msg = "415: サポã?トされなã�?ƒ¡ãƒ?‚£アタイプですã?"            ;       break;
523                            case 416                                                                                : msg = "416: 要求されたç¯?›²は不十åˆ?�§すã?"                           ;       break;  // 5.6.7.0 (2013/07/27)
524                            case 417                                                                                : msg = "417: 要求どおりの処ç�?�Œ不可能ですã?"                        ;       break;  // 5.6.7.0 (2013/07/27)
525                            case HttpURLConnection.HTTP_INTERNAL_ERROR              : msg = "500: å†?ƒ¨サーバエラーですã?"                                      ;       break;
526                            case HttpURLConnection.HTTP_NOT_IMPLEMENTED     : msg = "501: 実è£?�•れてã�?�¾せんã€?                                          ;       break;
527                            case HttpURLConnection.HTTP_BAD_GATEWAY                 : msg = "502: 誤ったゲートウェイですã?"                                    ;       break;
528                            case HttpURLConnection.HTTP_UNAVAILABLE                 : msg = "503: サービスが利用できませんã€?                            ;       break;
529                            case HttpURLConnection.HTTP_GATEWAY_TIMEOUT     : msg = "504: ゲートウェイが時間å?れですã?"                          ;       break;
530                            case HttpURLConnection.HTTP_VERSION                     : msg = "505: HTTP バã?ジョンがサポã?トされてã�?�¾せんã€?;       break;
531    //                      default : msg = "-1: 未定義" ;
532                            default : msg = code + ": 未定義" ;             // 5.6.7.0 (2013/07/27)
533                    }
534                    return msg ;
535            }
536    
537            /**
538             * サンプル実行用のメインメソãƒ?ƒ‰
539             *
540             * Usage: java org.opengion.fukurou.util.URLConnect [-info/-data] … url [user:passwd]
541             *
542             *   args[*] : [-info/-data]       æƒ??の取得か、データの取得かを指定しまã�?初期値:-data)ã€?
543             *   args[*] : [-post=ファイル名]  POSTメソãƒ?ƒ‰を指定して、ファイルãƒ??タをé?信しまã�?初期値:-get)ã€?
544             *   args[*] : [-encode=UTF-8]     エンコードをæŒ?®šしまã�?通常は接続å?のencodeを使用)
545             *   args[*] : [-out=ファイル名]   結果をファイルに出力しますã?ファイルエンコードもæŒ?®šしますã?
546             *   args[*] : [-errEx=true/false] trueの場合ã??šス?Ž゚ンス?º?°??¾žがã€?XX,5XX の時に RuntimeException を投げまã�?初期値:false)ã€?
547             *   args[A] : url                 ?µ?²?¬を指定しますã?GETの場合ã?パラメータは ?KEY=VALですã?
548             *   args[B] : [user:passwd]       BASIC認証のエリアへのアクセス時にæŒ?®šしますã?
549             *
550             * @og.rev 5.6.7.0 (2013/07/27) -errEx 追åŠ?
551             *
552             * @param       args    コマンド引数配å?
553             * @throws IOException 入出力エラーが発生したとã�?
554             */
555            public static void main( final String[] args ) throws IOException {
556                    if( args.length < 3 ) {
557                            LogWriter.log( "Usage: java org.opengion.fukurou.util.URLConnect [-info/-data] … url [user:passwd]"                            );
558                            LogWriter.log( "   args[*] : [-info/-data]       æƒ??の取得か、データの取得かを指定しまã�?初期値:-data)"                        );
559                            LogWriter.log( "   args[*] : [-post=ファイル名]  POSTメソãƒ?ƒ‰を指定して、ファイルãƒ??タをé?信しまã�?初期値:-get)"  );
560                            LogWriter.log( "   args[*] : [-encode=UTF-8]     エンコードをæŒ?®šしますã?(通常は接続å?のencodeを使用)"                              );
561                            LogWriter.log( "   args[*] : [-out=ファイル名]   結果をファイルに出力しますã?ファイルエンコードもæŒ?®šしまã�?              );
562                            LogWriter.log( "   args[*] : [-errEx=true/false] trueの場合ã??šス?Ž゚ンス?º?°??¾žがã€?XX,5XX の時に RuntimeException を投げまã�?初期値:false)" );
563                            LogWriter.log( "   args[A] : url                 ?µ?²?¬を指定しますã?GETの場合ã?パラメータは ?KEY=VALでã�?                    );
564                            LogWriter.log( "   args[B] : [user:passwd]       BASIC認証のエリアへのアクセス時にæŒ?®šしまã�?                                              );
565                            return;
566                    }
567    
568                    boolean isInfo  = false ;
569                    boolean isPost  = false ;
570                    String postKey  = null ;
571                    String postFile = null ;
572                    String encode   = null ;
573                    String outFile  = null ;
574                    boolean isEx    = false ;                               // 5.6.7.0 (2013/07/27) 追åŠ?
575                    String[] vals   = new String[2];                // url,userPass のé ?�«引数設å®?
576    
577                    int adrs = 0;
578                    for( int i=0; i<args.length; i++ ) {
579                            String arg = args[i];
580                            if( arg.equalsIgnoreCase( "-info" ) ) {
581                                    isInfo = true;
582                            }
583                            else if( arg.equalsIgnoreCase( "-data" ) ) {
584                                    isInfo = false;
585                            }
586                            else if( arg.startsWith( "-post=" ) ) {
587                                    isPost = true;
588                                    int sepAdrs = arg.indexOf( ':',6 );
589                                    postKey  = arg.substring( 6,sepAdrs );
590                                    postFile = arg.substring( sepAdrs+1 );
591                            }
592                            else if( arg.startsWith( "-encode=" ) ) {
593                                    encode = arg.substring( 8 );
594                            }
595                            else if( arg.startsWith( "-out=" ) ) {
596                                    outFile = arg.substring( 5 );
597                            }
598                            else if( arg.startsWith( "-errEx=" ) ) {                                                        // 5.6.7.0 (2013/07/27) 追åŠ?
599                                    isEx = "true".equalsIgnoreCase( arg.substring( 7 ) );
600                            }
601                            else if( arg.startsWith( "-" ) ) {
602                                    System.out.println( "Error Argment:" + arg );
603                            }
604                            else {
605                                    vals[adrs++] = arg;
606                            }
607                    }
608    
609                    String urlStr   = vals[0] ;
610                    String userPass = vals[1] ;
611    
612                    URLConnect conn = new URLConnect( urlStr,userPass );
613    
614                    // POST ãƒ??タは、connect() する前に、設定しますã?
615                    if( isPost ) {
616                            FileString file = new FileString();
617                            file.setFilename( postFile );
618                            String postData = file.getValue();
619    
620                            conn.setPostData( XHTMLTag.urlEncode(postKey, postData) );
621                    }
622    
623                    conn.connect();
624                    if( encode != null ) {
625                            conn.setCharset( encode );              // encode æŒ?®?
626                    }
627                    else {
628                            encode = conn.getCharset();             // æŒ?®šがなければ、接続å?の charset を使用
629                    }
630    
631                    final PrintWriter writer ;
632                    if( outFile != null ) {
633                            writer = FileUtil.getPrintWriter( new File( outFile ),encode );
634                    }
635                    else {
636                            writer = FileUtil.getLogWriter( "System.out" );
637                    }
638    
639                    int code = conn.getCode();              // 5.6.7.0 (2013/07/27) レスポンスコードã?、常に拾っておきますã?
640                    if( isInfo ) {
641                            writer.println( "URL    :" + conn.getUrl() );
642                            writer.println( "Type   :" + conn.getType() );
643    //                      writer.println( "Code   :" + conn.getCode() );
644                            writer.println( "Code   :" + code );                                    // 5.6.7.0 (2013/07/27) 取得済みの値を利用ã€?
645                            writer.println( "Message:" + conn.getMessage() );
646                            writer.println( "Charset:" + conn.getCharset() );
647                    }
648                    else {
649                            writer.println( conn.readData() );
650                    }
651    
652                    conn.disconnect();
653    
654                    Closer.ioClose( writer );
655    
656                    // 5.6.7.0 (2013/07/27) trueの場合ã??šス?Ž゚ンス?º?°??¾žがã€?XX,5XX の時に RuntimeException を投げまã�?
657                    if( isEx && code >= 400 ) {
658                            String errMsg = URLConnect.code2Message( code );
659                            throw new RuntimeException( errMsg );
660                    }
661            }
662    }