org.apache.commons.httpclient.protocol.Protocol类的使用及代码示例

x33g5p2x  于2022-01-26 转载在 其他  
字(13.0k)|赞(0)|评价(0)|浏览(156)

本文整理了Java中org.apache.commons.httpclient.protocol.Protocol类的一些代码示例,展示了Protocol类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Protocol类的具体详情如下:
包路径:org.apache.commons.httpclient.protocol.Protocol
类名称:Protocol

Protocol介绍

[英]A class to encapsulate the specifics of a protocol. This class class also provides the ability to customize the set and characteristics of the protocols used.

One use case for modifying the default set of protocols would be to set a custom SSL socket factory. This would look something like the following:

Protocol myHTTPS = new Protocol( "https", new MySSLSocketFactory(), 443 ); 
Protocol.registerProtocol( "https", myHTTPS );

[中]封装协议细节的类。该类还提供了定制所用协议集和特性的能力。
修改默认协议集的一个用例是设置自定义SSL套接字工厂。这将类似于以下内容:

Protocol myHTTPS = new Protocol( "https", new MySSLSocketFactory(), 443 ); 
Protocol.registerProtocol( "https", myHTTPS );

代码示例

代码示例来源:origin: commons-httpclient/commons-httpclient

/**
 * Lazily registers the protocol with the given id.
 * 
 * @param id the protocol ID
 * 
 * @return the lazily registered protocol
 * 
 * @throws IllegalStateException if the protocol with id is not recognized
 */
private static Protocol lazyRegisterProtocol(String id) 
  throws IllegalStateException {
  if ("http".equals(id)) {
    final Protocol http 
      = new Protocol("http", DefaultProtocolSocketFactory.getSocketFactory(), 80);
    Protocol.registerProtocol("http", http);
    return http;
  }
  if ("https".equals(id)) {
    final Protocol https 
      = new Protocol("https", SSLProtocolSocketFactory.getSocketFactory(), 443);
    Protocol.registerProtocol("https", https);
    return https;
  }
  throw new IllegalStateException("unsupported protocol: '" + id + "'");
}

代码示例来源:origin: commons-httpclient/commons-httpclient

/**
 * Set the given host. Uses the default protocol("http") and its port.
 * 
 * @param host The host(IP or DNS name).
 */
public synchronized void setHost(final String host) {
  Protocol defaultProtocol = Protocol.getProtocol("http"); 
  setHost(host, defaultProtocol.getDefaultPort(), defaultProtocol);
}

代码示例来源:origin: commons-httpclient/commons-httpclient

/**
 * Return true if the specified object equals this object.
 * @param obj The object to compare against.
 * @return true if the objects are equal.
 */
public boolean equals(Object obj) {
  
  if (obj instanceof Protocol) {
    
    Protocol p = (Protocol) obj;
    
    return (
      defaultPort == p.getDefaultPort()
      && scheme.equalsIgnoreCase(p.getScheme())
      && secure == p.isSecure()
      && socketFactory.equals(p.getSocketFactory()));
    
  } else {
    return false;
  }
  
}

代码示例来源:origin: elastic/elasticsearch-hadoop

protected Protocol keepProtocol(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))) {
        return oldProtocol;
      }
    }
    return Protocol.getProtocol(scheme);
  }
}

代码示例来源:origin: igniterealtime/Spark

Protocol.registerProtocol( "https", new Protocol( "https", new EasySSLProtocolSocketFactory(), 443 ) );
final HttpClient httpclient = new HttpClient();
      httpclient.getHostConfiguration().setProxy( proxyHost, Integer.parseInt( proxyPort ) );
  int result = httpclient.executeMethod( post );
  if ( result != 200 )

代码示例来源:origin: com.belerweb/weibo4j-oauth2

public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) {
 connectionManager = new MultiThreadedHttpConnectionManager();
 HttpConnectionManagerParams params = connectionManager.getParams();
 params.setDefaultMaxConnectionsPerHost(maxConPerHost);
 params.setConnectionTimeout(conTimeOutMs);
 params.setSoTimeout(soTimeOutMs);
 HttpClientParams clientParams = new HttpClientParams();
 // 忽略cookie 避免 Cookie rejected 警告
 clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
 client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager);
 Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
 Protocol.registerProtocol("https", myhttps);
 this.maxSize = maxSize;
 // 支持proxy
 if (proxyHost != null && !proxyHost.equals("")) {
  client.getHostConfiguration().setProxy(proxyHost, proxyPort);
  client.getParams().setAuthenticationPreemptive(true);
  if (proxyAuthUser != null && !proxyAuthUser.equals("")) {
   client.getState().setProxyCredentials(AuthScope.ANY,
     new UsernamePasswordCredentials(proxyAuthUser, proxyAuthPassword));
   log("Proxy AuthUser: " + proxyAuthUser);
   log("Proxy AuthPassword: " + proxyAuthPassword);
  }
 }
}

代码示例来源:origin: milgner/TeamCityRedmine

private InputStream fetchUrlWithRedmineHeader(String _url) throws IOException {
 try {
  HttpClient httpClient = new HttpClient();
  HttpMethod httpMethod = null;
  if (_url.toLowerCase().startsWith("https:") && ignoreSSL) {
   HttpsURL url = new HttpsURL(_url);
   Protocol easyhttps = new Protocol("https", new org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(), url.getPort());
   httpClient.getHostConfiguration().setHost(url.getHost(), url.getPort(), easyhttps);
   httpMethod = new GetMethod(url.getPath());
  } else {
   httpMethod = new GetMethod(_url);
  }
  httpMethod.setRequestHeader("X-Redmine-API-Key", apiToken);
  httpClient.executeMethod(httpMethod);
  return httpMethod.getResponseBodyAsStream();
 } catch (URIException e) {
  // too lazy to write exception handling :P
  throw new RuntimeException(e.getMessage());
 }
}

代码示例来源:origin: foxinmy/weixin4j

public HttpComponent3Factory() {
  httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
  httpClient.getParams().setHttpElementCharset(Consts.UTF_8.name());
  httpClient.getParams().setParameter("http.protocol.uri-charset",
      Consts.UTF_8.name());
  // httpMethod.getParams().setUriCharset(Consts.UTF_8.name());
  httpClient.getParams().setContentCharset(Consts.UTF_8.name());
  Protocol.registerProtocol("https",
      new Protocol("https", new SSLProtocolSocketFactory(
          HttpClientFactory.allowSSLContext()), 443));
}

代码示例来源:origin: org.alfresco/alfresco-repository

public BitlyUrlShortenerImpl()
{
  httpClient = new HttpClient();
  httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
  HostConfiguration hostConfiguration = new HostConfiguration();
  hostConfiguration.setHost("api-ssl.bitly.com", 443, Protocol.getProtocol("https"));
  httpClient.setHostConfiguration(hostConfiguration);
}

代码示例来源:origin: iipc/openwayback

protected synchronized HttpClient initialValue() {
    HttpClientParams params = new HttpClientParams();
    params.setParameter(HttpClientParams.RETRY_HANDLER, noRetryHandler);
    IPHttpConnectionManager manager = new IPHttpConnectionManager();
    Protocol dnsTimedProtocol = new Protocol("http",
        new DNSTimingProtocolSocketFactory(), 80);
    Protocol.registerProtocol("http", dnsTimedProtocol);
    manager.getParams().setConnectionTimeout(connectionTimeoutMS);
    manager.getParams().setSoTimeout(socketTimeoutMS);
    return new HttpClient(params, manager);
  }
};

代码示例来源:origin: smartrics/RestFixture

public static URI newURI(HttpMethod m, HostConfiguration conf) throws URIException {
    String scheme = conf.getProtocol().getScheme();
    String host = conf.getHost();
    int port = conf.getPort();
    return new URIBuilder().getURI(scheme, host, port, m.getPath(),
        m.getQueryString(), m.getParams());
  }
}

代码示例来源:origin: Alfresco/alfresco-repository

public void testSuccessfulVerifyTargetOverHttps() throws Exception
{
  
  //Stub HttpClient so that executeMethod returns a 200 response
  when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
      any(HttpState.class))).thenReturn(200);
  target.setEndpointProtocol(HTTPS_PROTOCOL);
  target.setEndpointPort(HTTPS_PORT);
  
  //Call verifyTarget
  transmitter.verifyTarget(target);
  
  ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
  ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
  ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
  
  verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
  
  assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort());
  assertTrue("socket factory", 
      hostConfig.getValue().getProtocol().getSocketFactory() instanceof SecureProtocolSocketFactory);
  assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(), 
      hostConfig.getValue().getProtocol().getScheme().toLowerCase());
}

代码示例来源:origin: foxinmy/weixin4j

private void resolveHttpParams(HttpParams params) {
  if (params != null) {
    if (params.getProxy() != null) {
      InetSocketAddress socketAddress = (InetSocketAddress) params
          .getProxy().address();
      httpClient.getHostConfiguration().setProxy(
          socketAddress.getHostName(), socketAddress.getPort());
    }
    if (params.getSSLContext() != null) {
      Protocol.registerProtocol("https", new Protocol("https",
          new SSLProtocolSocketFactory(params.getSSLContext()),
          443));
    }
    httpClient.getHttpConnectionManager().getParams()
        .setConnectionTimeout(params.getConnectTimeout());
  }
}

代码示例来源:origin: org.n52.metadata/smarteditor-api

private void initClient() {
  this.setClient(new HttpClient());
  HostConfiguration lConfig = new HostConfiguration();
  ProxyResolver proxyResolver = new ProxyResolver();
  try {
    URL lUrl = new URL(getEndpoint());
    ProxyHost lProxyHost = proxyResolver.createProxyHost(lUrl);
    lConfig.setProxyHost(lProxyHost);
    if (lProxyHost != null) {
      LOG.debug("Using proxy: Host={}; Port{};Scheme={}", lProxyHost.getHostName(), lProxyHost.getPort(), lProxyHost.getProtocol().getScheme());
    } else {
      LOG.debug("Using no proxy");
    }
    // set proxy authentication, if any
    Credentials lCredentials = proxyResolver.createCredentials(lUrl);
    if (lCredentials != null) {
      LOG.info("Setting proxy credentials");
      HttpState state = new HttpState();
      state.setProxyCredentials(AuthScope.ANY, lCredentials);
      getClient().setState(state);
    }
  } catch (MalformedURLException pEx) {
    LOG.error("Error cleating proxy for URL " + getEndpoint() + ": " + pEx.getMessage());
  }
  getClient().setHostConfiguration(lConfig);
}

代码示例来源:origin: apache/cloudstack

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);
  }
}

代码示例来源:origin: org.alfresco/alfresco-core

protected HttpClient getHttpsClient(String httpsHost, int httpsPort)
{
  // Configure a custom SSL socket factory that will enforce mutual authentication
  HttpClient httpClient = constructHttpClient();
  HttpHostFactory hostFactory = new HttpHostFactory(new Protocol("https", sslSocketFactory, httpsPort));
  httpClient.setHostConfiguration(new HostConfigurationWithHostFactory(hostFactory));
  httpClient.getHostConfiguration().setHost(httpsHost, httpsPort, "https");
  return httpClient;
}

代码示例来源:origin: com.addc/addc-ssl

/**
 * Setup the Httpclient for using TLS/SSL
 * 
 * @param httpClient
 *            The Httpclient to set up
 * @param url
 *            The target URL
 * @param sslConfiguration
 *            The SSLConfiuration to use
 * @throws GeneralSecurityException
 *             If the socket factory cannot be initialized
 */
public void setUpHttps(HttpClient httpClient, URL url, SSLConfiguration sslConfiguration)
    throws GeneralSecurityException {
  ProtocolSocketFactory protoSocketFactory= new LocalSecureSocketFactory(sslConfiguration.getClientKeystore(),
      sslConfiguration.getClientKeystorePassword(), sslConfiguration.getTrustStore());
  Protocol authhttps= new Protocol("https", protoSocketFactory, 443);
  Protocol.registerProtocol("https", authhttps);
  httpClient.getHostConfiguration().setHost(url.getHost(), url.getPort(), authhttps);
}

代码示例来源:origin: org.opensaml/opensaml

/**
 * 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);
}

代码示例来源:origin: commons-httpclient/commons-httpclient

/**
 * Sets the given host and port.  Uses the default protocol "http".
 * 
 * @param host the host(IP or DNS name)
 * @param port The port
 */
public synchronized void setHost(final String host, int port) {
  setHost(host, port, Protocol.getProtocol("http"));
}

代码示例来源:origin: org.mule.transports/mule-transport-http

@Override
public synchronized void setHost(URI uri)
{
  try
  {
    Protocol original = getProtocol();

    if (uri.getScheme().equals(original.getScheme()))
    {
      Protocol newProtocol = new Protocol(uri.getScheme(), original.getSocketFactory(),
        original.getDefaultPort());

        super.setHost(uri.getHost(), uri.getPort(), newProtocol);
    }
    else
    {
      Protocol protoByName = Protocol.getProtocol(uri.getScheme());
      super.setHost(uri.getHost(), uri.getPort(), protoByName);
    }
  }
  catch (URIException uriException)
  {
    throw new IllegalArgumentException(uriException);
  }
}

相关文章