下面列出了怎么用org.apache.commons.httpclient.protocol.ProtocolSocketFactory的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Register custom Socket Factory to let user accept or reject certificate
*/
public static void register() {
String urlString = Settings.getProperty("davmail.url");
try {
URL url = new URL(urlString);
String protocol = url.getProtocol();
if ("https".equals(protocol)) {
int port = url.getPort();
if (port < 0) {
port = HttpsURL.DEFAULT_PORT;
}
Protocol.registerProtocol(url.getProtocol(),
new Protocol(protocol, (ProtocolSocketFactory) new DavGatewaySSLProtocolSocketFactory(), port));
}
} catch (MalformedURLException e) {
DavGatewayTray.error(new BundleMessage("LOG_INVALID_URL", urlString));
}
}
private void doSSL( HttpClient client, HostConfiguration hostConf, String host, int port){
if (hostConf.getProtocol().isSecure()) {
// System.setProperty("javax.net.ssl.trustStore", sslKeystore);
// Protocol sslPprotocol = new Protocol("https", new
// org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(),
// 443);
// client.getHostConfiguration().setHost(host, 443, sslPprotocol);
try {
ProtocolSocketFactory factory = new InsecureSSLProtocolSocketFactory();
Protocol https = new Protocol("https", factory, port);
Protocol.registerProtocol("https", https);
client.getHostConfiguration().setHost(host, port, https);
} catch (GeneralSecurityException e) {
throw new CoreException(CoreException.SSL, e);
}
}
}
public static IService getService() throws MalformedURLException {
// Service srvcModel = new ObjectServiceFactory().create(IService.class);
// XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
// .newInstance().getXFire());
//
// IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
// return srvc;
ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
Protocol.registerProtocol(HTTP_TYPE, protocol);
Service serviceModel = new ObjectServiceFactory().create(IService.class,
SERVICE_NAME, SERVICE_NAMESPACE, null);
IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);
Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();
client.addOutHandler(new DOMOutHandler());
client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");
client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");
return service;
}
public static IService getService() throws MalformedURLException {
// Service srvcModel = new ObjectServiceFactory().create(IService.class);
// XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
// .newInstance().getXFire());
//
// IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
// return srvc;
ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
Protocol.registerProtocol(HTTP_TYPE, protocol);
Service serviceModel = new ObjectServiceFactory().create(IService.class,
SERVICE_NAME, SERVICE_NAMESPACE, null);
IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);
Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();
client.addOutHandler(new DOMOutHandler());
client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");
client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");
return service;
}
public static IService getService() throws MalformedURLException {
// Service srvcModel = new ObjectServiceFactory().create(IService.class);
// XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
// .newInstance().getXFire());
//
// IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
// return srvc;
ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
Protocol.registerProtocol(HTTP_TYPE, protocol);
Service serviceModel = new ObjectServiceFactory().create(IService.class,
SERVICE_NAME, SERVICE_NAMESPACE, null);
IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);
Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();
client.addOutHandler(new DOMOutHandler());
client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");
client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");
return service;
}
public static IService getService() throws MalformedURLException {
// Service srvcModel = new ObjectServiceFactory().create(IService.class);
// XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
// .newInstance().getXFire());
//
// IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
// return srvc;
ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
Protocol.registerProtocol(HTTP_TYPE, protocol);
Service serviceModel = new ObjectServiceFactory().create(IService.class,
SERVICE_NAME, SERVICE_NAMESPACE, null);
IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);
Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();
client.addOutHandler(new DOMOutHandler());
client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");
client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");
return service;
}
static void replaceProtocol(ProtocolSocketFactory socketFactory, String schema, int defaultPort) {
//
// switch protocol
// due to how HttpCommons work internally this dance is best to be kept as is
//
Protocol directHttp = Protocol.getProtocol(schema);
if (directHttp instanceof DelegatedProtocol) {
// unwrap the original
directHttp = ((DelegatedProtocol)directHttp).getOriginal();
assert directHttp instanceof DelegatedProtocol == false;
}
Protocol proxiedHttp = new DelegatedProtocol(socketFactory, directHttp, schema, defaultPort);
// NB: register the new protocol since when using absolute URIs, HttpClient#executeMethod will override the configuration (#387)
// NB: hence why the original/direct http protocol is saved - as otherwise the connection is not closed since it is considered different
// NB: (as the protocol identities don't match)
// this is not really needed since it's being replaced later on
// hostConfig.setHost(proxyHost, proxyPort, proxiedHttp);
Protocol.registerProtocol(schema, proxiedHttp);
// end dance
}
@Test
public void testProtocolReplacement() throws Exception {
final ProtocolSocketFactory socketFactory = getSocketFactory();
CommonsHttpTransport.replaceProtocol(socketFactory, "https", 443);
Protocol protocol = Protocol.getProtocol("https");
assertThat(protocol, instanceOf(DelegatedProtocol.class));
DelegatedProtocol delegatedProtocol = (DelegatedProtocol) protocol;
assertThat(delegatedProtocol.getSocketFactory(), sameInstance(socketFactory));
assertThat(delegatedProtocol.getOriginal(), sameInstance(original));
// ensure we do not re-wrap a delegated protocol
CommonsHttpTransport.replaceProtocol(socketFactory, "https", 443);
protocol = Protocol.getProtocol("https");
assertThat(protocol, instanceOf(DelegatedProtocol.class));
delegatedProtocol = (DelegatedProtocol) protocol;
assertThat(delegatedProtocol.getSocketFactory(), sameInstance(socketFactory));
assertThat(delegatedProtocol.getOriginal(), sameInstance(original));
}
public MonitorServlet(Properties properties, ExecutorWrapper executorWrapper) {
this.properties = properties;
this.executorWrapper = executorWrapper;
ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory();
Protocol https = new Protocol("https", socketFactory, 443);
Protocol.registerProtocol("https", https);
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("URL not set! Please give an URL as argument.");
System.exit(-1);
}
try {
String urlStrg = args[0];
URL url = new URL(urlStrg);
if (!HTTPS.equals(url.getProtocol())) {
throw new IllegalArgumentException("Please choose https protocol! " + url);
}
Protocol.registerProtocol(
HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory) new SSLConnector(), 443));
HttpMessage msg = accessURL(url);
if (msg != null) {
System.out.println(msg.getResponseHeader());
}
System.out.println("--- END of call -------------------------------------------------");
} catch (MalformedURLException e) {
e.printStackTrace();
}
System.out.close();
System.err.close();
}
public static IService getService() throws MalformedURLException {
// Service srvcModel = new
// ObjectServiceFactory().create(IService.class);
// XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
// .newInstance().getXFire());
//
// IService srvc = (IService) factory.create(srvcModel,
// Constants.CONNECT_URL);
// return srvc;
ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
Protocol.registerProtocol(HTTP_TYPE, protocol);
Service serviceModel = new ObjectServiceFactory().create(
IService.class, SERVICE_NAME, SERVICE_NAMESPACE, null);
IService service = (IService) new XFireProxyFactory().create(
serviceModel, SERVICE_URL);
Client client = ((XFireProxy) Proxy.getInvocationHandler(service))
.getClient();
client.addOutHandler(new DOMOutHandler());
client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE,
"1");
client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");
return service;
}
/**
* Set the custom trust manager as the ssl protocol handler for the stub
*
* @param stub
* @throws Exception
*/
public static void setSSLProtocolHandler(Stub stub) throws Exception {
init();
stub._getServiceClient()
.getOptions()
.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER,
new Protocol("https", (ProtocolSocketFactory) new CustomSSLProtocolSocketFactory(sslCtx), 443));
}
public static IService getService() throws MalformedURLException {
// Service srvcModel = new
// ObjectServiceFactory().create(IService.class);
// XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
// .newInstance().getXFire());
//
// IService srvc = (IService) factory.create(srvcModel,
// Constants.CONNECT_URL);
// return srvc;
ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
Protocol.registerProtocol(HTTP_TYPE, protocol);
Service serviceModel = new ObjectServiceFactory().create(
IService.class, SERVICE_NAME, SERVICE_NAMESPACE, null);
IService service = (IService) new XFireProxyFactory().create(
serviceModel, SERVICE_URL);
Client client = ((XFireProxy) Proxy.getInvocationHandler(service))
.getClient();
client.addOutHandler(new DOMOutHandler());
client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE,
"1");
client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");
return service;
}
public BigSwitchBcfApi() {
_client = createHttpClient();
_client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
try {
// Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), _port));
} catch (IOException e) {
S_LOGGER.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
}
}
protected NeutronRestApi(final Class<? extends HttpMethodBase> httpClazz, final String protocol, final int port) {
client = createHttpClient();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
this.httpClazz = httpClazz;
try {
// Cast to ProtocolSocketFactory to avoid the deprecated constructor
// with the SecureProtocolSocketFactory parameter
Protocol.registerProtocol(protocol, new Protocol(protocol, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT));
} catch (IOException e) {
s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
}
}
/**
* Establishes a connection to the specified host and port
* (via a proxy if specified).
* The underlying socket is created from the {@link ProtocolSocketFactory}.
*
* @throws IOException if an attempt to establish the connection results in an
* I/O error.
*/
public void open() throws IOException {
LOG.trace("enter HttpConnection.open()");
final String host = (proxyHostName == null) ? hostName : proxyHostName;
final int port = (proxyHostName == null) ? portNumber : proxyPortNumber;
assertNotOpen();
if (LOG.isDebugEnabled()) {
LOG.debug("Open connection to " + host + ":" + port);
}
try {
if (this.socket == null) {
usingSecureSocket = isSecure() && !isProxied();
// use the protocol's socket factory unless this is a secure
// proxied connection
ProtocolSocketFactory socketFactory = null;
if (isSecure() && isProxied()) {
Protocol defaultprotocol = Protocol.getProtocol("http");
socketFactory = defaultprotocol.getSocketFactory();
} else {
socketFactory = this.protocolInUse.getSocketFactory();
}
this.socket = socketFactory.createSocket(
host, port,
localAddress, 0,
this.params);
}
/*
"Nagling has been broadly implemented across networks,
including the Internet, and is generally performed by default
- although it is sometimes considered to be undesirable in
highly interactive environments, such as some client/server
situations. In such cases, nagling may be turned off through
use of the TCP_NODELAY sockets option." */
socket.setTcpNoDelay(this.params.getTcpNoDelay());
socket.setSoTimeout(this.params.getSoTimeout());
int linger = this.params.getLinger();
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
int sndBufSize = this.params.getSendBufferSize();
if (sndBufSize >= 0) {
socket.setSendBufferSize(sndBufSize);
}
int rcvBufSize = this.params.getReceiveBufferSize();
if (rcvBufSize >= 0) {
socket.setReceiveBufferSize(rcvBufSize);
}
int outbuffersize = socket.getSendBufferSize();
if ((outbuffersize > 2048) || (outbuffersize <= 0)) {
outbuffersize = 2048;
}
int inbuffersize = socket.getReceiveBufferSize();
if ((inbuffersize > 2048) || (inbuffersize <= 0)) {
inbuffersize = 2048;
}
inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
isOpen = true;
} catch (IOException e) {
// Connection wasn't opened properly
// so close everything out
closeSocketAndStreams();
throw e;
}
}
/**
* Establishes a connection to the specified host and port
* (via a proxy if specified).
* The underlying socket is created from the {@link ProtocolSocketFactory}.
*
* @throws IOException if an attempt to establish the connection results in an
* I/O error.
*/
public void open() throws IOException {
LOG.trace("enter HttpConnection.open()");
final String host = (proxyHostName == null) ? hostName : proxyHostName;
final int port = (proxyHostName == null) ? portNumber : proxyPortNumber;
assertNotOpen();
if (LOG.isDebugEnabled()) {
LOG.debug("Open connection to " + host + ":" + port);
}
try {
if (this.socket == null) {
usingSecureSocket = isSecure() && !isProxied();
// use the protocol's socket factory unless this is a secure
// proxied connection
ProtocolSocketFactory socketFactory = null;
if (isSecure() && isProxied()) {
Protocol defaultprotocol = Protocol.getProtocol("http");
socketFactory = defaultprotocol.getSocketFactory();
} else {
socketFactory = this.protocolInUse.getSocketFactory();
}
this.socket = socketFactory.createSocket(
host, port,
localAddress, 0,
this.params);
}
/*
"Nagling has been broadly implemented across networks,
including the Internet, and is generally performed by default
- although it is sometimes considered to be undesirable in
highly interactive environments, such as some client/server
situations. In such cases, nagling may be turned off through
use of the TCP_NODELAY sockets option." */
socket.setTcpNoDelay(this.params.getTcpNoDelay());
socket.setSoTimeout(this.params.getSoTimeout());
int linger = this.params.getLinger();
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
int sndBufSize = this.params.getSendBufferSize();
if (sndBufSize >= 0) {
socket.setSendBufferSize(sndBufSize);
}
int rcvBufSize = this.params.getReceiveBufferSize();
if (rcvBufSize >= 0) {
socket.setReceiveBufferSize(rcvBufSize);
}
int outbuffersize = socket.getSendBufferSize();
if ((outbuffersize > 2048) || (outbuffersize <= 0)) {
outbuffersize = 2048;
}
int inbuffersize = socket.getReceiveBufferSize();
if ((inbuffersize > 2048) || (inbuffersize <= 0)) {
inbuffersize = 2048;
}
inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
isOpen = true;
} catch (IOException e) {
// Connection wasn't opened properly
// so close everything out
closeSocketAndStreams();
throw e;
}
}
private void registerSsl() {
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new DefaultSslProtocolSocketFactory(), 443));
}
/**
* Configures the HTTP client
*/
private void configureClient() {
// Set up an HTTPS socket factory that accepts self-signed certs.
ProtocolSocketFactory factory = new SSLProtocolSocketFactory();
Protocol https = new Protocol("https", factory, 443);
Protocol.registerProtocol("https", https);
HttpConnectionManagerParams params = connectionManager.getParams();
params.setConnectionTimeout(timeout);
params.setSoTimeout(timeout);
params.setSendBufferSize(BUFFER_SIZE);
params.setReceiveBufferSize(BUFFER_SIZE);
params.setMaxTotalConnections(maxThreadsTotal);
// executeMethod(HttpMethod) seems to ignore the connection timeout on the connection manager.
// set it explicitly on the HttpClient.
client.getParams().setConnectionManagerTimeout(timeout);
HostConfiguration hostConf = client.getHostConfiguration();
ArrayList<Header> headers = new ArrayList<Header>();
// Set the User Agent in the header
headers.add(new Header("User-Agent", userAgent));
// prefer English
headers.add(new Header("Accept-Language", acceptLanguage));
// prefer UTF-8
headers.add(new Header("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.7"));
// prefer understandable formats
headers.add(new Header("Accept",
"text/html,application/xml;q=0.9,application/xhtml+xml,text/xml;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"));
// accept gzipped content
headers.add(new Header("Accept-Encoding", "x-gzip, gzip, deflate"));
hostConf.getParams().setParameter("http.default-headers", headers);
// HTTP proxy server details
if (useProxy) {
hostConf.setProxy(proxyHost, proxyPort);
if (proxyUsername.length() > 0) {
AuthScope proxyAuthScope = getAuthScope(
this.proxyHost, this.proxyPort, this.proxyRealm);
NTCredentials proxyCredentials = new NTCredentials(
this.proxyUsername, this.proxyPassword,
Http.agentHost, this.proxyRealm);
client.getState().setProxyCredentials(
proxyAuthScope, proxyCredentials);
}
}
}
DelegatedProtocol(ProtocolSocketFactory factory, Protocol original, String scheme, int port) {
super(scheme, factory, port);
this.original = original;
}
private void initSSLCertPolicy() {
EasySSLProtocolSocketFactory secureProtocolSocketFactory = new EasySSLProtocolSocketFactory();
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)secureProtocolSocketFactory, 443));
}
/**
* Sets the socket factory used to create sockets to the HTTP server.
*
* @see <a href="http://jakarta.apache.org/commons/httpclient/sslguide.html">HTTPClient SSL guide</a>
*
* @param newSocketFactory the socket factory used to produce sockets used to connect to the server
*
* @deprecated set this information on HTTP client used by provider
*/
public void setSocketFactory(ProtocolSocketFactory newSocketFactory) {
log.debug("Using the custom socket factory {} to connect to the HTTP server", newSocketFactory.getClass()
.getName());
Protocol protocol = new Protocol(metadataURI.getScheme(), newSocketFactory, metadataURI.getPort());
httpClient.getHostConfiguration().setHost(metadataURI.getHost(), metadataURI.getPort(), protocol);
}
/**
* By default this class uses the standard SSLProtocolSocketFactory, but this method allows this to be overridden.
* Useful if, for example, one wishes to permit support of self-signed certificates on the target.
* @param socketFactory ProtocolSocketFactory
*/
public void setHttpsSocketFactory(ProtocolSocketFactory socketFactory)
{
protocolMap.put(HTTPS_SCHEME_NAME, new Protocol(HTTPS_SCHEME_NAME, socketFactory, DEFAULT_HTTPS_PORT));
}