📄 httptransportagent.java
字号:
/*
* Copyright (C) 2003-2007 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.funambol.syncml.spds;
import com.funambol.util.StreamReaderFactory;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.Connector;
import javax.microedition.io.ConnectionNotFoundException;
import com.funambol.util.Log;
/**
* Represents a HTTP client implementation
**/
public final class HttpTransportAgent implements TransportAgent {
// --------------------------------------------------------------- Constants
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_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";
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 Data
private final String userAgent ;
private String requestURL ;
private final String charset ;
private String contentType;
// Compression parameters
private int sizeThreshold;
private boolean enableCompression;
private String responseDate;
// ------------------------------------------------------------ Constructors
/**
* Initialize a new HttpTransportAgent with a URL only
* The default userAgent and charset will be used.
*
* @param requestURL must be non-null.
*
*/
public HttpTransportAgent(String requestURL, boolean compress) {
this(requestURL, null, null, compress);
}
/**
* Initialize a new HttpTransportAgent with a URL and a userAgent string.
* The default charset will be used.
*
* @param requestURL must be non-null
* @param userAgent a string to be used as userAgent.
*/
public HttpTransportAgent(String requestURL, final String userAgent, boolean compress) {
this(requestURL, userAgent, null, compress);
}
/**
* 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 ) {
if (requestURL == null) {
throw new NullPointerException(
"TransportAgent: request URL parameter is null");
}
this.userAgent = userAgent;
this.requestURL = requestURL ;
this.charset = charset ;
this.sizeThreshold = 0;
this.enableCompression = compress;
this.responseDate = null;
Log.info("HttpTransportAgent - enableCompression: " + enableCompression);
}
// ---------------------------------------------------------- Public methods
/**
* Send a message using the default charset.
*
* @param requestURL must be non-null
* @param charset a valid charset, UTF-8 is used by default.
*
*/
public String sendMessage(String request) throws SyncException {
return sendMessage(request, this.charset);
}
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(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);
}
}
/**
*
* @param request HTTP request
* @return HTTP response
*/
public byte[] sendMessage(byte[] request) throws SyncException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
byte[] data = null;
try {
System.gc(); //XXX
try { Thread.sleep(1); } catch (InterruptedException ex) {
Log.error(this, "interruptedException in sendMessage");
ex.printStackTrace();
}
c = (HttpConnection)Connector.open(requestURL,
Connector.READ_WRITE, true);
//Request Configuration: Added ACCEPT ENCODING Parameter
setConfig(c, request.length);
os = c.openOutputStream();
os.write(request);
os.close();
os = null;
Log.debug("HttpTransportAgent: message sent, waiting for response.");
//Receive response on is Inputstream
is = c.openInputStream();
long len = c.getLength();
// Check http error
if (c.getResponseCode() != c.HTTP_OK) {
throw new SyncException(SyncException.SERVER_ERROR,
"Http error: " + c.getResponseMessage());
}
responseDate = c.getHeaderField(PROP_DATE);
//Log.debug("Date from server: " + responseDate);
contentType = c.getHeaderField(PROP_CONTENT_ENCODING);
Log.debug("Encoding Response Type from server: " + contentType);
data = StreamReaderFactory.getStreamReader(contentType)
.readStream(is, (int)len);
Log.debug("Stream correctly processed.");
} catch (ConnectionNotFoundException e) {
String msg = "HttpTransportAgent: can't open connection -->"
+ e.toString() ;
os=null;
Log.error(msg);
throw new SyncException(SyncException.ACCESS_ERROR, msg);
} catch (IOException e) {
String msg = "HttpTransportAgent: connection broken --> "
+ e.toString() ;
Log.error(msg);
throw new SyncException(SyncException.ACCESS_ERROR, msg);
} catch (IllegalArgumentException e) {
String msg = "HttpTransportAgent: invalid argument for connection --> "
+ e.toString() ;
Log.error(msg);
throw new SyncException(SyncException.ACCESS_ERROR, msg);
}
finally {
if (is != null) {
try {
is.close();
is=null;
}
catch(IOException ioe){
ioe.printStackTrace();
Log.error("sendmessage: can't close input stream.");
}
}
if (os != null) {
try {
os.close();
os=null;
}
catch(IOException ioe){
Log.error("sendmessage: can't close output stream.");
}
}
if (c != null) {
try {
c.close();
c=null;
}
catch(IOException ioe){
ioe.printStackTrace();
Log.error("sendmessage: can't close connection.");
}
}
}
return data;
}
// ---------------------------------------------------------- Private methods
/**
* Add request properties for the configuration, profiles,
* and locale of this system.
* @param c current HttpConnection to receive user agent header
*/
private void setConfig(HttpConnection c, int length) throws IOException {
String ua = this.userAgent;
String locale = System.getProperty(PROP_MICROEDITION_LOCALE);
if (ua == null) {
// Build the default user agent
String conf = System.getProperty(PROP_MICROEDITION_CONFIGURATION);
String prof = System.getProperty(PROP_MICROEDITION_PROFILES);
ua = "Profile/" + prof + " Configuration/" + conf ;
}
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty(PROP_CONTENT_TYPE, "application/vnd.syncml+xml");
c.setRequestProperty(PROP_CONTENT_LENGTH, String.valueOf(length));
// workaround to avoid errors on server
// the client user agent must not be sent with User-Agent header
c.setRequestProperty(PROP_USER_AGENT, "Funambol Java Mail" );
// we use Device-Agent for such an issue
c.setRequestProperty(PROP_DEVICE_AGENT, ua );
//Set Encoding and accepted properties: inflater or Gzip input Stream
if (enableCompression){
c.setRequestProperty(PROP_ACCEPT_ENCODING, COMPRESSION_TYPE_GZIP);
Log.debug("Encoding Response Required from Client: " + COMPRESSION_TYPE_GZIP);
}
if (this.sizeThreshold != 0) {
c.setRequestProperty(PROP_SIZE_THRESHOLD,
String.valueOf(this.sizeThreshold));
}
if (locale != null) {
c.setRequestProperty(PROP_CONTENT_LANGUAGE, locale);
}
}
public void enableCompression (boolean enable) {
this.enableCompression = enable;
}
public void setThreshold(int threshold) {
this.sizeThreshold = threshold;
}
public void setRequestURL(String requestURL) {
this.requestURL = requestURL;
}
/**
* Returns the last response date, if available, or null.
*/
public String getResponseDate() {
return responseDate;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -