curl的HTTP 200响应,但java的响应是401

时间:2017-01-21 19:06:46

标签: java http ssl curl jks

大家好我是SSL的新手。所以如果你发现任何愚蠢的问题,请原谅我。所以我的问题是当我试图通过CURL向客户端发送XML消息时我得到200 / OK作为响应代码但是当我尝试使用java代码时,我得到了400和401的响应。这是我的卷曲命令。

卷曲-v -H'内容类型:application / xml' -X PUT -d @ new.xml --cert /home/ipc/hpOMItest.pem:L83soGGSK2a --user testusername:testpassword -k https://clientURL/rest/9.10/synchronization/event

new.xml

    <event_change>
        <event_ref>
                 <event_id>4e784c68-d8d2-71e6-1bce-0a2555530000</event_id>
        </event_ref>
        <changed_properties>
                 <state>closed</state>
        </changed_properties>
    </event_change>

Java代码

    public class HPOMiUtil {
        private static final Log LOG = LogFactory.getLog(HPOMiUtil.class);
        private Map<String, SynchBackUrlDTO> httpPostFactory;
        private String pathKeyStore;
        private String passwordKeyStore;
        private String passwordPrivateKey = "testpassword";

        CloseableHttpClient client;

        public int closeNotification(Map<String, String> attributes) {

            String eventID = attributes.get(HPomiTicketUpdateHandler.EVENT_ID);
            int responseCode = 0;
            HttpPut post = null;
            String response;
            String requestXml = "<event_change>" + "<event_ref>" + "<event_id>" + eventID + "</event_id>" + "</event_ref>"
                    + "<changed_properties>" + "<state>closed</state>" + "</changed_properties>" + "</event_change>";

            SynchBackUrlDTO synchBackUrlDTO = null;
            try {
                synchBackUrlDTO = httpPostFactory.get(attributes.get(RadarTicketUpdateListener.SENDING_SERVER));
                if (synchBackUrlDTO != null) {
                    post = synchBackUrlDTO.getHttpPost();
                    post.setEntity(new StringEntity(requestXml));
                    post.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE);

                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(synchBackUrlDTO.getUsername(),
                            synchBackUrlDTO.getPassword());
                    post.addHeader(new BasicScheme().authenticate(creds, post, null));

                    client = getNewHttpsClient();

                    CloseableHttpResponse httpResponse = client.execute(post);
                    responseCode = httpResponse.getStatusLine().getStatusCode();
                    response = streamToStringAndCloseStream(httpResponse.getEntity().getContent(), "UTF-8");
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        LOG.info("Received response from HP OMi: " + response);
                    } else {
                        LOG.info("Received error response from HP OMi: " + response);
                        LOG.info("Response Code : " + responseCode);
                    }
                } else {
                    LOG.info("Not a registered sending address :"
                            + attributes.get(RadarTicketUpdateListener.SENDING_SERVER));
                    responseCode = 1;
                }
            } catch (Exception e) {
                LOG.info("Exception communication with API at-- " + post.getURI() + ": " + e);
                response = null;
                responseCode = 0;
            } finally {
                if (post != null)
                    post.releaseConnection();
            }
            return responseCode;
        }

        public CloseableHttpClient getNewHttpsClient() throws Exception {

            SSLContext sslcontext = getNewSSLContext();
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            client = HttpClients.custom().setSSLSocketFactory(factory).build();

            return (CloseableHttpClient) client;
        }

        private SSLContext getNewSSLContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
                IOException, KeyManagementException, UnrecoverableKeyException {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            FileInputStream instream = new FileInputStream(new File(pathKeyStore));
            try {
                keyStore.load(instream, passwordKeyStore.toCharArray());
                LOG.info("Values of TrustStore" + keyStore.size() + "    " + keyStore.toString());
                LOG.info("Path of Keystore " + pathKeyStore);
            } finally {
                instream.close();
            }

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, passwordPrivateKey.toCharArray());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom());
            return sslContext;
        }

        private String streamToStringAndCloseStream(InputStream stream, String charSet) throws IOException {
            StringBuilder rbuf = new StringBuilder();
            char[] cbuf = new char[1024];
            Reader reader = new InputStreamReader(stream, charSet);
            int read;
            do {
                read = reader.read(cbuf, 0, cbuf.length);
                if (read > 0) {
                    rbuf.append(cbuf, 0, read);
                }
            } while (read >= 0);
            reader.close();
            stream.close();
            return rbuf.toString();
        }
    }

factoryHttpPost的Spring配置不要带名字实际上HttpPut不发布

    <util:map id="factoryHttpPost">
            <entry key="@synchback.url.SendingServer.1@">
                <bean class="xx.yy.SynchBackUrlDTO">
                    <property name="username" value="@synchback.url.username.1@" />
                    <property name="password" value="@synchback.url.password.1@" />
                    <property name="httpPost">
                        <bean class="org.apache.http.client.methods.HttpPut">
                            <constructor-arg type="java.lang.String" value="@synchback.url.httpurl.1@"/>
                        </bean>
                    </property>
                </bean>
            </entry>
    </util:map>

我从CURL客户端获得的响应是​​200,从java我得到以下响应,并在不同服务器上的两个不同组件上部署相同的代码。

服务器-1

HPOMiUtil INFO - 从HP OMi收到错误响应:

Apache Tomcat / 7.0.42 - 错误报告

HTTP状态401 -

类型状态报告

消息

描述此请求需要HTTP身份验证。

Apache Tomcat / 7.0.42

[2017-01-21 07:27:59,806] [radarEventListenerContainer-1] HPOMiUtil INFO - 回复码:401

服务器2

[2017-01-21 09:24:47,363] [com.espertech.esper.Inbound-default-1] n.i.i.Director INFO - Received error response from HP OMi: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
The number of request header fields exceeds this server's limit.</p>
</body></html>

[2017-01-21 09:24:47,363] [com.espertech.esper.Inbound-default-1] n.i.i.Director INFO - 回复代码:400`

请提出宝贵的意见,以便我可以尝试一些我现在所缺少的东西。在此先感谢。

0 个答案:

没有答案