代码之家  ›  专栏  ›  技术社区  ›  frIT

从需要证书的Java访问URL[重复]

  •  0
  • frIT  · 技术社区  · 7 年前

    我对证书一无所知,希望能得到任何关于我做错了什么的指导……不幸的是,我无法在StackOverflow的其余部分或web上的其他地方找到解决方案。

    我有一个URL(使用HTTPS),我应该从中获得响应。(就我而言,这是一个图像,但我相信这不那么重要。)

    1.从web浏览器访问URL

    2.安装证书并从浏览器重试

    现在Chrome可以很好地检索资源。 Firefox仍然显示403,因此在选项下>高级>证书>查看我导入PFX的证书。现在FF还返回资源fine。

    3.JVM下安装证书

    我现在想用Java调用相同的URL。出于遗留目的,我仍在使用Java 7。我知道应该使用 keytool

    现在运行命令: keytool -import -alias MY_ALIAS -keystore C:/PROGRA~1/Java/jdk1.7.0_80/jre/lib/security/cacerts -file my_cert.cer

    keytool -list -v -keystore C:/PROGRA~1/Java/jdk1.7.0_80/jre/lib/security/cacerts

    现在我运行Java程序:

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.InetSocketAddress;
    import java.net.Proxy;
    import java.net.URL;
    import java.net.URLConnection;
    
    public class TestUrlRead {    
        private static final String PROXY_URL   = ...;
        private static final int    PROXY_PORT  = ...;
        private static final String IMAGE_URL   = ...;
    
        public static void main(String[] args) throws Exception {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_URL, PROXY_PORT));
            URL url = new URL(IMAGE_URL);
            URLConnection con = url.openConnection(proxy);
            con.setDoOutput(true);
            con.connect();
            InputStream webIn = con.getInputStream(); // <-- causes IOException
            // read and use webIn
            inReader.close();
        }
    }
    

    Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: ...
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
        at TestUrlRead.main(TestUrlRead.java:33)
    

    响应和计时表明,这类似于没有证书的浏览器。我做错了什么?

    1 回复  |  直到 7 年前
        1
  •  0
  •   user207421    7 年前

    我再次将证书从Chrome导出为这种格式。

    javax.net.ssl.keyStore/keyStoreType/keyStorePassword this question 如何做到这一点。