从其他项目调用java servlet

时间:2018-03-14 11:01:57

标签: java

我有一个Java Web Project(演示1),它运行在安装在Ubuntu 14.04服务器上的Apache Tomcat V8.0.33上。

现在我正在创建一个新的Java Web项目(演示2),我必须使用我的项目(演示2)中已经运行的项目(演示1)的请求参数调用Servlet(doPost)。

我的Java Web Project(演示1)正在 https 上运行 所以Servlet URL是https://shibbolethidp.demo.local/idp/j_security_check

我还使用下面的服务器命令导出证书,其中Demo 1 App运行到我的本地jdk,我正在尝试运行我的Demo 2 App。

C:\Program Files\Java\jdk1.8.0_60\bin\keytool.exe -import -alias shib-idp -file C:\Users\guest\Desktop\Desktop\shib_exportedCert.der -keystore "C:\Program Files\Java\jdk1.8.0_60\jre\lib\security\cacerts" -storepass changeit

我的演示2项目代码如下所示,我用它来调用演示1项目的Servlet

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

@SuppressWarnings("serial")
public class Authn extends HttpServlet {
    Logger log = Logger.getLogger(Authn.class.getName());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            URL url = new URL("https://shibbolethidp.demo.local/idp/j_security_check");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            out.write("xml=xmltest\r\n");
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String response1;
            while ((response1 = in.readLine()) != null) {
                System.out.println(response1);
            }
            in.close();
        } catch (Exception e) {
        }
    }
}

但是当我运行这个时,我收到以下错误

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching shibbolethidp.demo.local found

我使用的是jdk1.8.0_60和Tomcat 8。

1 个答案:

答案 0 :(得分:0)

您可以为localhost开发环境使用传输安全(SSL)解决方法。

尝试添加此内容:

public class Authn extends HttpServlet {
    Logger log = Logger.getLogger(Authn.class.getName());

    static {
        //for localhost testing only
        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
        new javax.net.ssl.HostnameVerifier(){

            public boolean verify(String hostname,
                    javax.net.ssl.SSLSession sslSession) {
                if (hostname.equals("localhost")) {
                    return true;
                }
                return false;
            }
        });
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
      // your code here
    }
}