java - 如何检查客户端是否在Java中使用PoolingHttpClientConnectionManager

原文 标签 java ssl connection-pooling

我正在尝试使用我正在使用的客户端代码在服务器上配置连接池(Https SSL Configured)
PoolingHttpClientConnectionManager和我有连接池的工作代码,但我想知道天气我的代码正在使用PoolingHttpClientConnectionManager还是不知道如何解决

如果我的代码未使用池管理器,如何使用它

我的代码:

static PoolingHttpClientConnectionManager cm ;
    static CloseableHttpClient httpClient;
    static
    {


        SslConfigurator sslConfig = SslConfigurator.newInstance()
                .securityProtocol("TLS")
                .keyStoreFile("/path")
                .keyStorePassword("passw")
                .keyStoreType("JKS")
                .trustStoreFile("/path");

        SSLContext sslCtx = sslConfig.createSSLContext();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslCtx,NoopHostnameVerifier.INSTANCE);
        HttpClientContext clientContext = HttpClientContext.create();


        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();


        cm = new PoolingHttpClientConnectionManager(registry);

        client = HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setConnectionManager(cm)
                .build();

    }
    public static void main(String a[]) throws ClientProtocolException, IOException, JSONException
    {

        JSONObject jsonResponse;




         StringEntity se = new StringEntity(jsonRequest.toString());

        HttpPost httpPost = new HttpPost(path);
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("Connection", "keep-alive");
        CloseableHttpResponse response2; 
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");



        int i;
        for(i=0;i<10;i++)
       {
            response2 = client.execute(httpPost);

        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();

        String result = EntityUtils.toString(entity2);
        System.out.println(result);

        Date date = new Date();
        System.out.println(dateFormat.format(date));
       response2.close();
       }

    }

最佳答案

面对如此复杂的问题时,这是一种经验法则...

创建一个简单的类,例如'BrokenPHCCM',该类扩展了org.apache.http.impl.conn.PoolingHttpClientConnectionManager,在这个新类中,只需重写org.apache.http.impl.conn.PoolingHttpClientConnectionManager#connect方法以基本上抛出一个java.lang.RuntimeException即可。

当您要将这种类型的实例传递给http客户端构建器.setConnectionManager(brokenCM)并尝试连接时,应该获得运行时异常,对吗?

这是我对此的简化版本

public static class BrokenPoolingHttpClientConnectionManager
          extends PoolingHttpClientConnectionManager 
{

    public BrokenPoolingHttpClientConnectionManager(
            Registry<ConnectionSocketFactory> socketFactoryRegistry) {

        super(socketFactoryRegistry);
    }

    @Override
    public void connect(
                    HttpClientConnection managedConn, 
                    HttpRoute route, 
                    int connectTimeout, 
                    HttpContext context) throws IOException  {

        throw new RuntimeException("As expected");
    }
}

static PoolingHttpClientConnectionManager cm;
static CloseableHttpClient httpClient;

static {

        HttpClientContext clientContext = HttpClientContext.create();

        final Registry<ConnectionSocketFactory>
            registry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .build();

        cm = new BrokenPoolingHttpClientConnectionManager(registry);

        httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .build();

}


public static void main(String a[]) throws ClientProtocolException, IOException, JSONException {

        HttpGet httpRequest = new HttpGet("http://www.google.com/");
        httpRequest.setHeader("Connection", "keep-alive");
        CloseableHttpResponse response2;
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");

        int i;
        for (i = 0; i < 10; i++) {
          response2 = httpClient.execute(httpRequest);

          System.out.println(String.format("response status=%s", response2.getStatusLine()));

          String result = EntityUtils.toString(response2.getEntity());
          System.out.println(String.format("response size=%d", result.length()));

          Date date = new Date();
          System.out.println(dateFormat.format(date));
          response2.close();
        }
}


您的控制台将显示以下内容:


  线程“主”中的异常java.lang.RuntimeException:如预期的那样
  com.something.Demo $ BrokenPoolingHttpClientConnectionManager.connect(Demo.java:43)
    在
  org.apache.http.impl.execchain.MainClientExec。EstablishmentRoute(MainClientExec.java:363)
    在
  org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
    在
  org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
    在
  org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
    在
  org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
    在
  org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    在
  org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    在
  org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    在com.something.Demo.main(Demo.java:78)
  sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)位于
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    在
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    在java.lang.reflect.Method.invoke(Method.java:606)在
  com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)


除此之外,您还应该依靠文档和诸如Java的静态类型化方面的东西:)

相关文章:

ssl - Elasticsearch NEST HttpClientHandler证书

javascript - Javascript中的ERR_INSECURE_RESPONSE处理技巧

ssl - OpenID空SSL上下文错误

java - 每个连接是否由数据库连接池中的一个线程支持?

java - 掷骰子程序

java - 用数组计算斐波那契数

java - 使用按钮从另一个类中的数组填充JTextArea

java - 练习访问修饰符

java - Tomcat 7会话超时,但postgres sql连接保持活动状态

java - 即使使用C3P0 +显式session.close(),休眠连接也不会关闭