📄 wapclient.java
字号:
/**
* JWAP - A Java Implementation of the WAP Protocols
* Copyright (C) 2001-2004 Niko Bender
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sourceforge.jwap;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Hashtable;
import net.sourceforge.jwap.util.Logger;
import net.sourceforge.jwap.wsp.CWSPMethodManager;
import net.sourceforge.jwap.wsp.CWSPResult;
import net.sourceforge.jwap.wsp.CWSPSession;
import net.sourceforge.jwap.wsp.CWSPSocketAddress;
import net.sourceforge.jwap.wsp.IWSPUpperLayer2;
import net.sourceforge.jwap.wsp.pdu.CWSPHeaders;
/**
* This class represents a WSP "User-Agent" which can be used for executing
* WSP <code>GET</code> and <code>POST</code> methods.
* <p>
* <h3>Example</h3>
* <pre>
* WAPClient client = new WAPClient("localhost", 9201);
* Request request = new GetRequest("http://localhost/");
* client.connect();
* Response response = client.execute(request);
* client.disconnect();
* </pre>
* @author Michel Marti
*
*/
public class WAPClient
{
private static final Logger log = Logger.getLogger(WAPClient.class);
static {
Logger.initLogSystem(true);
}
private static final String USAGE =
"Usage: WAPClient <WAP-Gateway-address[:port]> [GET/POST] [options] <URL>\n" +
" if method (GET/POST) is unspecified, GET is assumed\n\n" +
" Common options:\n" +
" -u <user-agent> The User-Agent (defaults to jWAP/1.x)\n" +
" -o <file> write response to file\n" +
" -v show response-headers\n\n" +
" POST options:\n" +
" -c <content-type> The content-type of the response body\n" +
" -p <file> A file containing the post data, use '-' to read" +
" the post data from standard input";
// Default timeouts
private static final long DEFAULT_CONNECT_TIMEOUT=30000;
private static final long DEFAULT_EXEC_TIMEOUT=180000;
private static final String DEFAULT_CONTENT_TYPE = "application/unknown";
private static final String CONNECTED = "CONNECTED";
private InetAddress gw;
private int port;
private CWSPSession session;
private byte[] sessionLock = new byte[0];
private IWSPUpperLayer2 upperLayerImpl;
private Hashtable pendingRequests;
private long connectTimeout = DEFAULT_CONNECT_TIMEOUT;
private long execTimeout = DEFAULT_EXEC_TIMEOUT;
private WAPClient() {}
/**
* Construct a new WAP Client
* @param wapGateway hostname of the WAP gateway to use
* @param port port-number
* @throws UnknownHostException if the hostname cannot be resolved
*/
public WAPClient(String wapGateway, int port) throws UnknownHostException
{
this(InetAddress.getByName(wapGateway), port);
}
/**
* Construct a new WAP Client
* @param wapGateway the address of the WAP gateway to use
* @param port the WAP gateway port number
*/
public WAPClient(InetAddress wapGateway, int port)
{
gw=wapGateway;
this.port=port;
upperLayerImpl = new UpperLayerImpl();
pendingRequests = new Hashtable();
}
/**
* Execute a request. The client must be connected to the gateway.
* @param request the request to execute
* @return the response
* @throws SocketException if a timeout occured
* @throws IllegalStateException if the client is not connected
*/
public Response execute(Request request) throws SocketException, IllegalStateException
{
CWSPMethodManager mgr = null;
synchronized(this)
{
if( session == null ) {
throw new IllegalStateException("Not yet connected");
}
CWSPHeaders headers = request.getWSPHeaders();
if( headers.getHeader("accept") == null ) {
headers.setHeader("accept","*/*");
}
if( headers.getHeader("user-agent") == null ) {
headers.setHeader("user-agent","jWAP/1.04");
}
if( request instanceof GetRequest ) {
if(log.isDebugEnabled()) {
log.debug("Executing GET Request for URL "+request.getURL());
}
mgr = session.s_get(headers, request.getURL());
} else if( request instanceof PostRequest ) {
if(log.isDebugEnabled()) {
log.debug("Executing POST Request for URL "+request.getURL());
}
PostRequest post = (PostRequest) request;
mgr = session.s_post(post.getWSPHeaders(), post.getRequestBody(), post.getContentType(), post.getURL());
}
}
// Wait until the method shows up in our hashtable
if(log.isDebugEnabled()) {
log.debug("Waiting "+execTimeout+"ms for execute completion...");
}
Response response = (Response) waitForCompletion(mgr,execTimeout);
if(response == null ) {
throw new SocketException("Timeout executing request");
}
return response;
}
/**
* Connect to the WAP gateway. Before requests can be executed, this method
* must be called.
* @throws SocketException if the connection could not be established
* @throws IllegalStateException if the client is already connected
*/
public synchronized void connect() throws SocketException, IllegalStateException
{
if( session != null ) {
throw new IllegalStateException("Already connected");
}
pendingRequests.clear();
if(log.isDebugEnabled()) {
log.debug("Establishing WSP session with "+gw.getHostName()+":"+port);
}
session = new CWSPSession(gw,port,upperLayerImpl);
session.s_connect();
Object result = waitForCompletion(sessionLock,connectTimeout);
if( result != null ) {
if( result instanceof CWSPSocketAddress[] ) {
// redirect received ...
CWSPSocketAddress[] addr = (CWSPSocketAddress[]) result;
if( addr.length > 0 ) {
// Take the first address and try to reconnect...
gw = addr[0].getAddress();
int p = addr[0].getPort();
if( p > 0 ) {
port = p;
}
session = null;
if(log.isDebugEnabled()) {
log.debug("Redirect to "+gw.getHostName()+":"+port);
}
connect();
return;
}
} else if( !CONNECTED.equals(result) ) {
CWSPSession ts = session;
session = null;
ts.s_disconnect();
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,connectTimeout);
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
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -