Httpclient设置帖子没有实际发布

时间:2016-12-01 13:26:27

标签: java post https request httpclient

我有以下代码,我只是通过httpslocalhost

提出请求
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(new FileInputStream(new File("keystore.p12")),
                "password".toCharArray());
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                new SSLContextBuilder()
                .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore, "password".toCharArray()).build());
        HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        ResponseEntity<String> response = restTemplate.getForEntity(
                "https://localhost:1810/bot", String.class);

但现在我想发送一个带身体的帖子请求,所以我添加了

        HttpPost post = new HttpPost("https://localhost:1810/bot");
        post.setHeader("Content-Type", "application/json");
        StringEntity params =new StringEntity(" { \"message\": \"hello\", \"sessionID\": \"\", \"timestamp\": \"1480596337583\" } ");
        post.setEntity(params);

但现在我不知道如何将它们结合起来。我发现的只有Httpclient.execute(post),但会将其作为http请求发送。 有没有办法将Httpclient设置为Post方法而不实际发送它,因为我必须将其作为参数提供给 ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); 还是有另一种解决方案?

1 个答案:

答案 0 :(得分:0)

你需要像这样创建一个HttpHost

HttpHost host = new HttpHost("domain", 443, "https")

然后使用带有host参数的execute()方法

httpClient.execute(host, post)