📄 httptransportagent.java
字号:
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program 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 General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.syncml.spds;
//import com.funambol.mailclient.ui.controller.UIController;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import com.funambol.util.Log;
import com.funambol.util.StreamReaderFactory;
//Commented out so IDE will not remove when organizing imports
import com.funambol.util.SyncListener;
//#ifdef isBlackberry
//# import com.funambol.util.BlackberryHelper;
//#elif isBlackberry_plugin
//# import com.funambol.util.BlackberryHelper;
//#endif
/**
* Represents a HTTP client implementation
**/
public final class HttpTransportAgent implements TransportAgent {
// --------------------------------------------------------------- Constants
private static final int NUM_RETRY = 3;
private static final String PROP_MICROEDITION_CONFIGURATION =
"microedition.configuration";
private static final String PROP_CONTENT_LANGUAGE =
"Content-Language";
private static final String PROP_CONTENT_LENGTH =
"Content-Length";
private static final String PROP_UNCOMPR_LENGHT =
"Uncompressed-Content-Length";
private static final String PROP_CONTENT_TYPE =
"Content-Type";
private static final String PROP_MICROEDITION_LOCALE =
"microedition.locale";
private static final String PROP_MICROEDITION_PROFILES =
"microedition.profiles";
private static final String PROP_USER_AGENT =
"User-Agent";
// specific property to send device identity to the server
private static final String PROP_DEVICE_AGENT =
"Device-Agent";
// Proprietary http header to avoid bugs of Nokia S60 3ed. FP1
// It forces the server to set a 'Set-Cookie' header not empty
private static final String PROP_FORCE_COOKIES =
"x-funambol-force-cookies";
private static final String PROP_ACCEPT_ENCODING = "Accept-Encoding";
private static final String PROP_CONTENT_ENCODING = "Content-Encoding";
private static final String PROP_DATE = "Date";
private static final String PROP_SIZE_THRESHOLD =
"Size-Threshold";
private static final String COMPRESSION_TYPE_GZIP = "gzip";
private static final String COMPRESSION_TYPE_ZLIB = "deflate";
private final String userAgent;
private final String charset;
private final int OPEN_CONNECTION = 0;
private final int WRITE_REQUEST = 1;
private final int READ_RESPONSE = 2;
private final int RESPONSE_CORRECTLY_PROCESSED = 3;
// ------------------------------------------------------------ Private Data
private String requestURL;
private String contentType;
// Compression parameters
private int sizeThreshold;
private boolean enableCompression;
private String responseDate;
private boolean forceCookies;
private int uncompressedLength;
private int retryOnWrite;
private int counter;
private int status = OPEN_CONNECTION;
private static HttpConnection c = null;
private static InputStream is = null;
private static OutputStream os = null;
private long CONNECTION_SLEEP_TIME = 10000;
// ------------------------------------------------------------ Constructors
/**
* Create a new HttpTransportAgent.
* @param requestURL is the url where to send the request; must not be null
* @param compress if true the http compression is enabled, disabled
* otherwise
* @param forceCookies
*/
public HttpTransportAgent(String requestURL, boolean compress,
boolean forceCookies) {
this(requestURL, null, null, compress, forceCookies);
}
/**
* Create a new HttpTransportAgent using the default charset.
* @param requestURL is the url where to send the request; must not be null
* @param userAgent the user agent parameter to be filled into the http
* headers
* @param compress if true the http compression is enabled, disabled
* otherwise
* @param forceCookies if true sets http headers to force the use of cookies
* instead of Url Rewriting to manage the current http session.
*/
public HttpTransportAgent(String requestURL, final String userAgent,
boolean compress, boolean forceCookies) {
this(requestURL, userAgent, null, compress, forceCookies);
}
/**
* Initialize a new HttpTransportAgent with a URL and a charset to use.
*
* @param requestURL must be non-null
* @param userAgent a string to be used as userAgent.
* @param charset a valid charset, the device charset is used by default.
*
*/
public HttpTransportAgent(String requestURL,
final String userAgent,
final String charset,
boolean compress,
boolean forceCookies) {
if (requestURL == null) {
throw new NullPointerException(
"TransportAgent: request URL parameter is null");
}
//#ifdef isBlackberry
//# if (retryOnWrite < BlackberryHelper.getConfigCount()) {
//# retryOnWrite = BlackberryHelper.getConfigCount();
//# Log.debug("[httpTransportAgent] bb found, increasing connection retry to " +
//# retryOnWrite);
//# }
//#elif isBlackberry_plugin
//# if (retryOnWrite < BlackberryHelper.getConfigCount()) {
//# retryOnWrite = BlackberryHelper.getConfigCount();
//# Log.debug("[httpTransportAgent] bb found, increasing connection retry to " +
//# retryOnWrite);
//# }
//#endif
retryOnWrite = NUM_RETRY;
this.userAgent = userAgent;
this.requestURL = requestURL;
this.charset = charset;
this.sizeThreshold = 0;
this.enableCompression = compress;
this.responseDate = null;
this.forceCookies = forceCookies;
Log.info("HttpTransportAgent - enableCompression: " + enableCompression);
Log.info("HttpTransportAgent - forceCookies: " + forceCookies);
}
// ---------------------------------------------------------- Public methods
/**
* Send a message using the default (UTF-8) charset.
* @param requestURL must be non-null
* @return String formatted http response
* @throws SyncException when the connection cannot be established with the
* server because the implementation tries to access a not existent url
* or when there are network coverage problems
*/
public String sendMessage(String request) throws SyncException {
return sendMessage(request, this.charset);
}
/**
* Send the http request specifying the required encoding charset for the
* http headers. and read the response
* @param request the http request body
* @param charset the charset to be included into the http headers
* @return String formatted http response
* @throws SyncException when the connection cannot be established with the
* server because the implementation tries to access a not existent url
* or when there are network coverage problems
*/
public String sendMessage(String request, String charset)
throws SyncException {
byte[] indata = null;
byte[] outdata = null;
if (charset != null) {
try {
indata = request.getBytes(charset);
} catch (UnsupportedEncodingException uee) {
Log.error("Charset " + charset + " not supported. Using default");
charset = null;
indata = request.getBytes();
}
} else {
indata = request.getBytes();
}
request = null;
outdata = sendMessage(indata);
indata = null;
if (outdata == null) {
String msg = "Response data null";
Log.error("[sendMessage] " + msg);
//throw new SyncException(SyncException.ACCESS_ERROR, msg);
throw new SyncException(SyncException.DATA_NULL, msg);
} else {
if (charset != null) {
try {
return new String(outdata, charset);
} catch (UnsupportedEncodingException uee) {
Log.error("Charset " + charset + " not supported. Using default");
charset = null;
return new String(outdata);
}
} else {
return new String(outdata);
}
}
}
/**
* Send the http request and read the response
* @param request the http request body
* @return byte[] raw http response
* @throws SyncException when the connection cannot be established with the
* server because the implementation tries to access a not existent url
* or when there are network coverage problems
*/
public byte[] sendMessage(byte[] request) throws SyncException {
byte[] data = null;
try {
//Open up a HTTP connection and sends the request to the server
//writing on the output stream
writeRequest(request);
//Read the server response from the input stream returned by the
//server and set the related byte array
data = readResponse(data);
//Exits the cicle only when the response is correctly read
if (status == RESPONSE_CORRECTLY_PROCESSED) {
return data;
}
} catch (ConnectionNotFoundException e) {
//This exception is implementation dependent and it is thrown
//when the requested url string is incorrect. This can depend by
//1) The requested URL doesn't exist
//doesn't exist);
//2) The required protocol (i.e. http://) is not correctly
//specified
String msg = "HttpTransportAgent: can't open connection -->" + e.toString();
Log.error(msg);
throw new SyncException(SyncException.CONN_NOT_FOUND, msg);
} catch (IllegalArgumentException e) {
String msg = "HttpTransportAgent: invalid argument for connection --> " + e.toString();
Log.error(msg);
throw new SyncException(SyncException.ILLEGAL_ARGUMENT, msg);
} finally {
clear();
}
//Return the byte[] corresponding to the read response
return data;
}
/**
* Enable the http "gzip" compression parameter usage
* @param enable enables "gzip" http header parameter to be written if true
*/
public void enableCompression(boolean enable) {
this.enableCompression = enable;
}
/**
* Set the http "Size-Threshold" header parameter
* @param threshold is the "Size-Threshold" value to be added to http
* headers
*/
public void setThreshold(int threshold) {
this.sizeThreshold = threshold;
}
/**
* Set the request's url
* @param requestURL the request's destination url
*/
public void setRequestURL(String requestURL) {
this.requestURL = requestURL;
}
/**
* Get the last response date
* @return the last response date (String format),
* if available, null otherwise
*/
public String getResponseDate() {
return responseDate;
}
/**
* Set the number of http writing attempts
* @param retryOnWrite the number of attempts to write http requests
*/
public void setRetryOnWrite(int retryOnWrite) {
this.retryOnWrite=retryOnWrite;
}
//---------------------------------------------------------- Private methods
private void openConnection(byte[] request, int i) throws IOException {
status = OPEN_CONNECTION;
//#ifdef low_mem
//# System.gc(); //XXX
//# try { Thread.sleep(1); } catch (InterruptedException ex) {
//# Log.error(this, "interruptedException in sendMessage");
//# ex.printStackTrace();
//# }
//#endif
String url = requestURL;
//#ifdef isBlackberry
//# if (BlackberryHelper.workingConfigHasBeenFound()) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -