0

安全な Web サイトに投稿リクエストを送信しています。私がウェブのようにそれをするとき

<body>
    <form method=POST action= "https://www.abc.com" >
        <textarea name="Request" rows="30%" cols="80%"></textarea>
        <br>
        <br>
        <br>
        <input type="Submit"> 
    </form>    
</body> 

私がすることは、xmlをtextaresに貼り付けてフォームを送信し、応答を取得することです。罰金。プレーンJavaから同じことをしようとすると、証明書の問題が発生します

sun.security.validator.ValidatorException: PKIX path building failed: 
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid 
certification path to requested target

SSL をバイパスすると、応答が返されsystemErrorます。なんで ?

ここで私がしていること

@Override
public HttpsURLConnection getHttpsConnection() throws Exception {   
    HttpsURLConnection urlConnection = null;

    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { 
            new X509TrustManager() {
                public void checkClientTrusted( final X509Certificate[] chain, final String authType ) {
                }

                public void checkServerTrusted( final X509Certificate[] chain, final String authType ) {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

            }       
    } ;

    // Install the all-trusting trust manager
    final SSLContext sslContext = SSLContext.getInstance("SSL");

    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {

        public boolean verify(String hostname, SSLSession session) {              
            return true;          
        }           
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    try {   
        URL myUrl = new URL(this.url);
        urlConnection = (HttpsURLConnection) myUrl.openConnection();    
    } catch (Exception e) { 
        throw new Exception("Error in getting connecting to url: " + url + " :: " + e.getMessage());

    }

    return urlConnection;

} //end of getHttpsConnection()

private void processHttpRequest(HttpsURLConnection connection, String method, Map<String, String> params) throws Exception {

    StringBuffer requestParams = new StringBuffer();

    if (params != null && params.size() > 0) {
           Iterator<String> paramIterator = params.keySet().iterator();
           while (paramIterator.hasNext()) {
               String key = paramIterator.next();
               String value = params.get(key);
               requestParams.append(URLEncoder.encode(key, "UTF-8"));
               requestParams.append("=").append(URLEncoder.encode(value, "UTF-8"));
               requestParams.append("&");

           }
    }

    try {

        connection.setUseCaches(false);
        connection.setDoInput(true);

        if ("POST".equals(method)) {    
            // set request method to POST
            connection.setDoOutput(true);

        } else {
            // set request method to GET
            connection.setDoOutput(false);

        }

        String parameters = requestParams.toString();

        if ("POST".equals(method) && params != null && params.size() > 0) {

            OutputStream os = connection.getOutputStream();
            DataOutputStream wr = new DataOutputStream(os);
            wr.writeBytes(URLEncoder.encode(parameters, "UTF-8"));
            wr.writeBytes(parameters);
            wr.flush();
            wr.close();

            /**
             * 

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(requestParams.toString());
            writer.flush();  
            writer.close();
           */
        }

     // reads response, store line by line in an array of Strings
      BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      List<String> response = new ArrayList<String>();

      String line = "";
      while ((line = reader.readLine()) != null) {
          response.add(line);
      }

      reader.close();

      String[] myResponse = (String[]) response.toArray(new String[0]);

      if (myResponse != null && myResponse.length > 0) {
          System.out.println("RESPONSE FROM: " + this.url);
          for (String myLine : response) {
              System.out.println(myLine);
          }
      }  
    } catch(Exception e) {  
        throw new Exception("Error in sending Post :: " + e.getMessage());

    }   
}

ここで私はそれをどのように呼んでいますか

String req = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    req = req + "<abc>";
     req = req + "   
     ....   
       req = req + " </xyz>";
    req = req + "</abc>";

StringBuffer buffer = new StringBuffer();

buffer.append(req);

HttpServices httpServices = context.getBean("httpService", HttpServices.class);

String method = "POST";
Map<String, String> params = new HashMap<String, String>();
params.put("request", buffer.toString());

try {

    HttpsURLConnection connection = httpServices.getHttpsConnection();
    httpServices.processHttpRequest(connection, method, params);

} catch (Exception e) {

    System.out.println(e.getMessage());

}

私はこのような応答を受け取ります。もちろん、私は正確な応答を示すことはできません。しかし、それはこのように見えます。

<?xml version="1.0" encoding="UTF-8"?>
<Result>
    <SystemError>
        <Message>87b24972</Message>
    </SystemError>
</Result>

プレーンな Java とは異なる応答が得られるのはなぜですか? SSLをバイパスして、Apache httpクライアントでも同じことを試しましたが、Apacheクライアントから同じ応答が得られます。

ありがとう。

4

2 に答える 2

0

私は問題を解決しました:)。問題は、コンテンツタイプを設定していなかったことです

connection.setUseCaches(false);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "text/xml"); //added

if ("POST".equals(method)) {   

    // set request method to POST
    connection.setDoOutput(true);

} else {

    // set request method to GET
    connection.setDoOutput(false);

}

コンテンツ タイプを追加した後、サーバーからの応答を取得し始めます。

于 2013-07-05T16:11:06.787 に答える
0

投稿の本文は次のようにする必要があります

Request=<?xml ...

のリクエスト パラメータの名前を忘れましたPOST

また、ValidatorException: PKIX path building failed少なくとも通信パートナーのルート証明書が必要です。Java のデフォルトの証明書には、必要なルート証明書が含まれていないようです。

于 2013-07-04T08:25:41.543 に答える