下面列出了怎么用org.apache.commons.httpclient.protocol.Protocol的API类实例代码及写法,或者点击链接到github查看源代码。
public HttpClientTransmitterImpl()
{
protocolMap = new TreeMap<String,Protocol>();
protocolMap.put(HTTP_SCHEME_NAME, httpProtocol);
protocolMap.put(HTTPS_SCHEME_NAME, httpsProtocol);
httpClient = new HttpClient();
httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
httpMethodFactory = new StandardHttpMethodFactoryImpl();
jsonErrorSerializer = new ExceptionJsonSerializer();
// Create an HTTP Proxy Host if appropriate system properties are set
httpProxyHost = HttpClientHelper.createProxyHost("http.proxyHost", "http.proxyPort", DEFAULT_HTTP_PORT);
httpProxyCredentials = HttpClientHelper.createProxyCredentials("http.proxyUser", "http.proxyPassword");
httpAuthScope = createProxyAuthScope(httpProxyHost);
// Create an HTTPS Proxy Host if appropriate system properties are set
httpsProxyHost = HttpClientHelper.createProxyHost("https.proxyHost", "https.proxyPort", DEFAULT_HTTPS_PORT);
httpsProxyCredentials = HttpClientHelper.createProxyCredentials("https.proxyUser", "https.proxyPassword");
httpsAuthScope = createProxyAuthScope(httpsProxyHost);
}
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 void inicializaCertificado(Certificado certificado, InputStream cacert) throws CertificadoException {
Optional.ofNullable(certificado).orElseThrow(() -> new IllegalArgumentException("Certificado não pode ser nulo."));
Optional.ofNullable(cacert).orElseThrow(() -> new IllegalArgumentException("Cacert não pode ser nulo."));
try {
KeyStore keyStore = getKeyStore(certificado);
if (certificado.isAtivarProperties()) {
CertificadoProperties.inicia(certificado, cacert);
} else {
SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(keyStore,certificado.getNome(),certificado.getSenha(), cacert,
certificado.getSslProtocol());
Protocol protocol = new Protocol("https", socketFactory, 443);
Protocol.registerProtocol("https", protocol);
}
} catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException | IOException e) {
throw new CertificadoException(e.getMessage());
}
}
public static javax.security.cert.X509Certificate getCert(String host, int port) {
GetCertSSLProtocolSocketFactory certFactory = new GetCertSSLProtocolSocketFactory();
Protocol myhttps = new Protocol("https", certFactory, port);
HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setHost(host, port, myhttps);
GetMethod httpget = new GetMethod("/");
try {
httpclient.executeMethod(httpget);
//System.out.println(httpget.getStatusLine());
} catch (Throwable t) {
//do nothing
}
finally {
httpget.releaseConnection();
}
return certFactory.getCertificate();
}
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);
}
}
}
/**
* Creates a new HTTP connection for the given host with the virtual
* alias and port via the given proxy host and port using the given
* protocol.
*
* @param proxyHost the host to proxy via
* @param proxyPort the port to proxy via
* @param host the host to connect to. Parameter value must be non-null.
* @param port the port to connect to
* @param protocol The protocol to use. Parameter value must be non-null.
*/
public HttpConnection(
String proxyHost,
int proxyPort,
String host,
int port,
Protocol protocol) {
if (host == null) {
throw new IllegalArgumentException("host parameter is null");
}
if (protocol == null) {
throw new IllegalArgumentException("protocol is null");
}
proxyHostName = proxyHost;
proxyPortNumber = proxyPort;
hostName = host;
portNumber = protocol.resolvePort(port);
protocolInUse = protocol;
}
/**
* Get a Protocol for the given parameters. The default implementation
* selects a protocol based only on the scheme. Subclasses can do fancier
* things, such as select SSL parameters based on the host or port. This
* method must not return null.
*/
protected Protocol getProtocol(HostConfiguration old, String scheme, String host, int port)
{
final Protocol oldProtocol = old.getProtocol();
if (oldProtocol != null) {
final String oldScheme = oldProtocol.getScheme();
if (oldScheme == scheme || (oldScheme != null && oldScheme.equalsIgnoreCase(scheme))) {
// The old protocol has the desired scheme.
return oldProtocol; // Retain it.
}
}
Protocol newProtocol = (scheme != null && scheme.toLowerCase().endsWith("s")) ? httpsProtocol
: httpProtocol;
if (newProtocol == null) {
newProtocol = Protocol.getProtocol(scheme);
}
return newProtocol;
}
@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));
}
/**
* Creates a new HTTP connection for the given host with the virtual
* alias and port via the given proxy host and port using the given
* protocol.
*
* @param proxyHost the host to proxy via
* @param proxyPort the port to proxy via
* @param host the host to connect to. Parameter value must be non-null.
* @param port the port to connect to
* @param protocol The protocol to use. Parameter value must be non-null.
*/
public HttpConnection(
String proxyHost,
int proxyPort,
String host,
int port,
Protocol protocol) {
if (host == null) {
throw new IllegalArgumentException("host parameter is null");
}
if (protocol == null) {
throw new IllegalArgumentException("protocol is null");
}
proxyHostName = proxyHost;
proxyPortNumber = proxyPort;
hostName = host;
portNumber = protocol.resolvePort(port);
protocolInUse = protocol;
}
/**
* Constructor for HttpHost.
*
* @param hostname the hostname (IP or DNS name). Can be <code>null</code>.
* @param port the port. Value <code>-1</code> can be used to set default protocol port
* @param protocol the protocol. Value <code>null</code> can be used to set default protocol
*/
public HttpHost(final String hostname, int port, final Protocol protocol) {
super();
if (hostname == null) {
throw new IllegalArgumentException("Host name may not be null");
}
if (protocol == null) {
throw new IllegalArgumentException("Protocol may not be null");
}
this.hostname = hostname;
this.protocol = protocol;
if (port >= 0) {
this.port = port;
} else {
this.port = this.protocol.getDefaultPort();
}
}
private void createHttpClient() {
Protocol protocol = Protocol.getProtocol("https");
if (protocol == null) {
// ZAP: Dont override an existing protocol - it causes problems with ZAP
Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyhttps);
}
initialState = new HttpState();
MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(1000);
connectionManager.getParams().setMaxTotalConnections(1000);
// connectionManager.set
httpclient = new HttpClient(connectionManager);
// httpclient.
}
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 net.fortuna.ical4j.model.Calendar getCalendar(String uid, ICalendar calendar)
throws ICalendarException, MalformedURLException {
net.fortuna.ical4j.model.Calendar cal = null;
PathResolver RESOLVER = getPathResolver(calendar.getTypeSelect());
Protocol protocol = getProtocol(calendar.getIsSslConnection());
URL url = new URL(protocol.getScheme(), calendar.getUrl(), calendar.getPort(), "");
ICalendarStore store = new ICalendarStore(url, RESOLVER);
try {
if (store.connect(calendar.getLogin(), calendar.getPassword())) {
List<CalDavCalendarCollection> colList = store.getCollections();
if (!colList.isEmpty()) {
CalDavCalendarCollection collection = colList.get(0);
cal = collection.getCalendar(uid);
}
} else {
throw new AxelorException(
TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
I18n.get(IExceptionMessage.CALENDAR_NOT_VALID));
}
} catch (Exception e) {
throw new ICalendarException(e);
} finally {
store.disconnect();
}
return cal;
}
private static String getHttpUrl(final String host, final int port, final URI uri, final HttpConnection httpConnection) throws URIException {
final Protocol protocol = httpConnection.getProtocol();
if (protocol == null) {
return uri.getURI();
}
final StringBuilder sb = new StringBuilder();
final String scheme = protocol.getScheme();
sb.append(scheme).append("://");
sb.append(host);
// if port is default port number.
if (port != SKIP_DEFAULT_PORT) {
sb.append(':').append(port);
}
sb.append(uri.getURI());
return sb.toString();
}
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 boolean saveMetadataFile(String spMetaDataURL, String metadataFileName) {
if (StringHelper.isEmpty(spMetaDataURL)) {
return false;
}
if (appConfiguration.getShibboleth3FederationRootDir() == null) {
throw new InvalidConfigurationException(
"Failed to save meta-data file due to undefined federation root folder");
}
HTTPFileDownloader.setEasyhttps(new Protocol("https", new EasyCASSLProtocolSocketFactory(), 443));
String metadataFileContent = HTTPFileDownloader.getResource(spMetaDataURL, "application/xml, text/xml", null,
null);
if (StringHelper.isEmpty(metadataFileContent)) {
return false;
}
String spMetadataFile = getIdpMetadataDir() + metadataFileName;
try {
return documentStoreService.saveDocument(spMetadataFile, metadataFileContent, UTF_8);
} catch (Exception ex) {
log.error("Failed to write meta-data file '{}'", spMetadataFile, ex);
}
return false;
}
private void uploadFile(File file, UploadRequest response, ChatRoom room, Message.Type type)
{
Log.warning("uploadFile request " + room.getRoomJid() + " " + response.putUrl);
URLConnection urlconnection = null;
try {
PutMethod put = new PutMethod(response.putUrl);
int port = put.getURI().getPort();
if (port > 0)
{
Protocol.registerProtocol( "https", new Protocol( "https", new EasySSLProtocolSocketFactory(), port ) );
}
HttpClient client = new HttpClient();
RequestEntity entity = new FileRequestEntity(file, "application/binary");
put.setRequestEntity(entity);
put.setRequestHeader("User-Agent", "Spark HttpFileUpload");
client.executeMethod(put);
int statusCode = put.getStatusCode();
String responseBody = put.getResponseBodyAsString();
Log.warning("uploadFile response " + statusCode + " " + responseBody);
if ((statusCode >= 200) && (statusCode <= 202))
{
broadcastUploadUrl(room.getRoomJid(), response.getUrl, type);
}
} catch (Exception e) {
Log.error("uploadFile error", 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;
}
protected HttpClient getHttpsClient(String httpsHost, int httpsPort)
{
// Configure a custom SSL socket factory that will enforce mutual authentication
HttpClient httpClient = constructHttpClient();
// Default port is 443 for the HostFactory, when including customised port (like 8983) the port name is skipped from "getHostURL" string
HttpHostFactory hostFactory = new HttpHostFactory(new Protocol("https", sslSocketFactory, HttpsURL.DEFAULT_PORT));
httpClient.setHostConfiguration(new HostConfigurationWithHostFactory(hostFactory));
httpClient.getHostConfiguration().setHost(httpsHost, httpsPort, "https");
return httpClient;
}
/**
* Sets the protocol used to establish the connection
*
* @param protocol The protocol to use.
*
* @throws IllegalStateException if the connection is already open
*/
public void setProtocol(Protocol protocol) {
assertNotOpen();
if (protocol == null) {
throw new IllegalArgumentException("protocol is null");
}
protocolInUse = protocol;
}
/**
* Select a Protocol to be used for the given host, port and scheme. The
* current Protocol may be selected, if appropriate. This method need not be
* thread-safe; the caller must synchronize if necessary.
* <p>
* This implementation returns the current Protocol if it has the given
* scheme; otherwise it returns the Protocol registered for that scheme.
*/
protected Protocol getNewProtocol(String host, int port, String scheme)
{
final Protocol oldProtocol = getProtocol();
if (oldProtocol != null) {
final String oldScheme = oldProtocol.getScheme();
if (oldScheme == scheme || (oldScheme != null && oldScheme.equalsIgnoreCase(scheme))) {
// The old {rotocol has the desired scheme.
return oldProtocol; // Retain it.
}
}
return Protocol.getProtocol(scheme);
}
public OMElement soapCall(OMElement body, Protocol protocol, String endpoint, String action)
throws XdsException {
try {
return new ServiceFinder(endpoint, action).invoke(body);
}
catch (Exception e) {
log.error(ExceptionUtil.exception_details(e));
throw new XdsException("SoapBypass call failed", e);
}
}
public void soapSend(OMElement body, Protocol protocol, String endpoint, boolean mtom,
boolean addressing, boolean soap12, String action)
throws XdsException, AxisFault {
this.expectedReturnAction = null;
this.mtom = mtom;
this.addressing = addressing;
this.soap12 = soap12;
soapSend(body, protocol, endpoint, action);
}
public void run() {
try {
Protocol protocol = ConnectionUtil.getProtocol(connection);
String epr = ConnectionUtil.getTransactionEndpoint(connection);
Soap soap = new Soap();
soap.soapCall(request, protocol, epr, mtom, true, true, action, null);
ag.store(homeId, soap.getResult());
}catch(Exception e){
String msg = "Fail to get a response from the community " + homeId + " - " + e.getMessage();
OMElement response = service.start_up_error(request, e, AppendixV.REGISTRY_ACTOR, msg);
service.generateLogMessage(response);
ag.store(homeId, response);
}
}
public Protocol getProtocol() {
if (hasConnection()) {
return wrappedConnection.getProtocol();
} else {
return null;
}
}
public void setProtocol(Protocol protocol) {
if (hasConnection()) {
wrappedConnection.setProtocol(protocol);
} else {
// do nothing
}
}
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);
}
}
/**
* Sets the protocol used to establish the connection
*
* @param protocol The protocol to use.
*
* @throws IllegalStateException if the connection is already open
*/
public void setProtocol(Protocol protocol) {
assertNotOpen();
if (protocol == null) {
throw new IllegalArgumentException("protocol is null");
}
protocolInUse = protocol;
}
/**
* Sets the given host, port and protocol.
*
* @param host the host(IP or DNS name)
* @param port The port
* @param protocol the protocol
*/
public synchronized void setHost(final String host, int port, final Protocol protocol) {
if (host == null) {
throw new IllegalArgumentException("host must not be null");
}
if (protocol == null) {
throw new IllegalArgumentException("protocol must not be null");
}
this.host = new HttpHost(host, port, protocol);
}