⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 wapclient.java

📁 WAP Stack implementation jwap.sourceforge.net
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                if( result == null ) {                    throw new SocketException("Timeout while establishing connection");                } else if( !CONNECTED.equals(result) ) {                    throw new SocketException("Connection failed.");                }            }        }        log.debug("Connection established");    }    /**     * Disconnect from the WAP gateway. This releases used resources as well.      */    public synchronized void disconnect()    {        if( session == null ) {            return;           }        log.debug("Disconnecting client...");        CWSPSession ts = session;        session = null;        ts.s_disconnect();        // Wait for confirmation        Object result = waitForCompletion(sessionLock,disconnectTimeout);        session = null;        log.debug("Client disconnected...");    }        /**     * Check if the client is currently connected to the WAP gateway     * @return true if the client is connected, false otherwise     */    public synchronized boolean isConnected() {        return session!=null;     }        /**     * Execute a WSP GET request.     *      * <pre>     * Usage: WAPClient &lt;WAP-Gateway-address[:port]&gt; [GET/POST] [options] &lt;URL&gt;     *   if method (GET/POST) is unspecified, GET is assumed     *      *   Common options:     *   -u <user-agent>   The User-Agent (defaults to jWAP/1.x)     *   -o <file>         write response to file     *   -v                show response-headers     *      * POST options:     *   -c <content-type> The content-type  of the response body     *   -p <file>         A file containing the post data, use '-' to read the post data from standard input     * </pre>     */    public static void main(String[] args) throws IOException {        if(args.length < 2 ) {            System.err.println(USAGE);            System.exit(1);        }        String wapGW = args[0];        int wapPort = 9201;                int c =wapGW.indexOf(':');        if( c > 0 ) {            wapPort = Integer.parseInt(wapGW.substring(c+1));            wapGW = wapGW.substring(0, c);        }                int argp=1;        String method = args[argp];        String userAgent = null;        String output = null;        boolean showHeaders = false;        String contentType = null;        String input = null;        String url = null;        String locaddr = null;        InetAddress la=null;        int lp = CWTPSocket.DEFAULT_PORT;        long tc = DEFAULT_CONNECT_TIMEOUT;        long tx = DEFAULT_EXEC_TIMEOUT;                if( "GET".equals(method) || "POST".equals(method) ) {            argp++;        }                         try {            while( url == null && argp < args.length )             {                String arg = args[argp++];                if( "-u".equals(arg) ) {                    userAgent=args[argp++];                } else if( "-o".equals(arg) ) {                    output = args[argp++];                } else if( "-v".equals(arg) ) {                    showHeaders=true;                   } else if( "-l".equals(arg) ) {                    locaddr = args[argp++];                } else if( "-c".equals(arg) ) {                    contentType = args[argp++];                } else if( "-p".equals(arg) ) {                    input = args[argp++];                   } else if( "-tc".equals(arg) ) {                  tc = Integer.parseInt(args[argp++])*1000;                } else if( "-tx".equals(arg) ) {                  tx = Integer.parseInt(args[argp++])*1000;                } else if( arg.startsWith("-") ){                    System.err.println(arg+": Unknown option");                    System.err.println(USAGE);                    System.exit(1);                } else {                    url = arg;                                     }            }        } catch( Exception unknown ) {            System.err.println(USAGE);            System.exit(1);           }                if( url == null ) {            System.err.println("Error: <URL> is mandatory");            System.err.println(USAGE);            System.exit(1);           }                if( locaddr != null ) {            locaddr=locaddr.trim();            int p = locaddr.lastIndexOf(':');            if( p >= 0 ) {                lp = Integer.parseInt(locaddr.substring(p+1));                locaddr=locaddr.substring(0,p);            }            if( ! "".equals(locaddr) ) {                la = InetAddress.getByName(locaddr);               }        }                WAPClient client = new WAPClient(InetAddress.getByName(wapGW), wapPort, la, lp);        Request request = null;        OutputStream out = null;                if( output == null || "-".equals(output) ) {            out = System.out;            } else {            out = new FileOutputStream(output);           }                if( "POST".equals(method) ) {            if( contentType == null ) {                System.err.println("Warning: no content-type specified, assuming "+DEFAULT_CONTENT_TYPE);                contentType = DEFAULT_CONTENT_TYPE;            }            byte[] postData = readPostData(input);                        PostRequest preq = new PostRequest(url);            request = preq;            preq.setContentType(contentType);            preq.setRequestBody(postData);        } else {            request = new GetRequest(url);        }        try {            client.connect(tc);            Response response = client.execute(request,tx);            if( out == System.out ) {                System.out.println("");               }            if( showHeaders || !response.isSuccess()) {                out.write(("Status: "+response.getStatus()+" "+response.getStatusText()+"\n").getBytes());                for(Enumeration e = response.getHeaderNames(); e.hasMoreElements(); ) {                    String key = (String) e.nextElement();                    for(Enumeration e2 = response.getHeaders(key); e2.hasMoreElements(); ) {                        String val = e2.nextElement().toString();                        out.write((key+": "+val+"\n").getBytes());                    }                }                out.write("\n".getBytes());            }            out.write(response.getResponseBody());        } finally {            client.disconnect();               if( out != null && out == System.out ) {                out.close();               }         }        System.exit(0);    }        private static byte[] readPostData(String input) throws IOException {        ByteArrayOutputStream out = new ByteArrayOutputStream();        InputStream in = null;        if( input == null ) {            System.out.println("Reading post-data from input stream, hit EOF when done");            in = System.in;        } else if( "-".equals(input)) {            in = System.in;        } else {            in = new FileInputStream(input);        }        byte[] buf = new byte[1024];        int read = 0;        while( (read=in.read(buf)) > 0 ) {            out.write(buf,0,read);        }        in.close();        return out.toByteArray();    }    private Object waitForCompletion(Object key, long timeout)    {        Object object = null;        long startAt = 0;                if( timeout > 0 ) {            startAt = System.currentTimeMillis();        }        while(object == null) {            if( timeout > 0 && (startAt + timeout) < System.currentTimeMillis()) {                log.debug("Timeout occurred");                break;               }            synchronized(pendingRequests) {                object = pendingRequests.remove(key);                if( object == null ) {                    try {                        pendingRequests.wait(timeout);                    } catch (InterruptedException e) {                        log.warn("Interrupted");                    }                }            }        }        return object;    }        private void complete(Object key, Object value)    {        synchronized(pendingRequests) {            pendingRequests.put(key, value);            pendingRequests.notifyAll();           }       }            // -----------------------------------------------------------    private class UpperLayerImpl implements IWSPUpperLayer2    {        // Connection established        public void s_connect_cnf() {            complete(sessionLock, CONNECTED);        }        public void s_disconnect_ind(short reason) {            if(log.isDebugEnabled()) {                log.debug("s_disconnect_ind("+reason+")");            }            complete(sessionLock, "DISCONNECTED: "+reason);            session = null;        }        public void s_disconnect_ind(CWSPSocketAddress[] redirectInfo) {            complete(sessionLock, redirectInfo);        }        public void s_methodResult_ind(CWSPResult result) {            Response response = new Response(result);            CWSPMethodManager mgr = result.getMethodManager();            // Acknowledge reception (TODO: arg should not be null)            mgr.s_methodResult(null);            complete(mgr, response);        }        public void s_suspend_ind(short reason) {            if(log.isDebugEnabled()) {                log.debug("s_suspend_ind("+reason+")");            }        }        public void s_resume_cnf() {            log.debug("s_resume_cnf()");        }        public void s_disconnect_ind(InetAddress[] redirectInfo) {        }        public void s_methodResult_ind(byte[] payload, String contentType, boolean moreData) {        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -