Java中的curl HTTPS实现

发布于 2024-11-02 18:49:49 字数 1549 浏览 1 评论 0原文

如何将此 PHP 代码转换为 java?如何建立 HTTPS 连接?

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $to_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

我将其用于 HTTP 我不能使用类似的东西

URL url = new URL("http://XZX");
            URLConnection con = url.openConnection();
            con.setDoInput(true);
            con.setConnectTimeout(40000);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setDefaultUseCaches(false);
            // tell the web server what we are sending
            con.setRequestProperty("Content-Type", "text/xml;charset=\"utf-8\"");
            con.setRequestProperty("Accept", "text/xml");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Pragma", "no-cache");
            con.setRequestProperty("SOAPAction", "\"run\"");
            con.setRequestProperty("Content-length", String.valueOf(requestXml.length()));
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            writer.write(requestXml);
            writer.flush();
            writer.close();
            InputStreamReader reader = new InputStreamReader(con.getInputStream());

How do I convert this PHP code to java? How do I make an HTTPS connection?

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $to_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

I use this for HTTP cant i use something similar

URL url = new URL("http://XZX");
            URLConnection con = url.openConnection();
            con.setDoInput(true);
            con.setConnectTimeout(40000);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setDefaultUseCaches(false);
            // tell the web server what we are sending
            con.setRequestProperty("Content-Type", "text/xml;charset=\"utf-8\"");
            con.setRequestProperty("Accept", "text/xml");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Pragma", "no-cache");
            con.setRequestProperty("SOAPAction", "\"run\"");
            con.setRequestProperty("Content-length", String.valueOf(requestXml.length()));
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            writer.write(requestXml);
            writer.flush();
            writer.close();
            InputStreamReader reader = new InputStreamReader(con.getInputStream());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谁对谁错谁最难过 2024-11-09 18:49:49

您需要考虑使用 Apache HTTP 组件。它具有用 Java 发出 Web 请求所需的所有功能。

如果您不想使用 Apache 库,Java 有一个内置的 HttpsURConnection 类,用于使用 HTTPS 连接。

You'll want to look into using Apache HTTP Components. This has all the functionality you need for making web requests in Java.

If you don't want to use the Apache library, Java has a built in HttpsURConnection class for connecting using HTTPS.

最舍不得你 2024-11-09 18:49:49

您应该使用类 HttpsURLConnection

但是,因为您在 curl 中使用了以下选项

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

您还需要设置不检查主机名的 HostNameVerifier 和不检查服务器证书有效性的 SSlSocketFactory。

可以使用这个小示例来完成:

// creating all trust manager. It will accept as valid any certificate.
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};
SSLContext sslContext = SSLContext.getInstance("SSL");
// set our friendly trust manager to ssl context. we pass it to connection later
sslContext.init(null, trustAllCerts, null); 
HttpsURLConnection connection = (HttpsURLConnection) (url).openConnection();
// set all trust manager to connection
connection.setSSLSocketFactory(sslContext.getSocketFactory());
// here we say not to check host name
connection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });

在您可以设置标头、超时之后,例如,就像您已经为 URLConnection 所做的那样

You should use class HttpsURLConnection

But, because you use following options in curl

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

you need also set HostNameVerifier which don't check host name and SSlSocketFactory which don't check server certificate validity.

It can be done using this little sample:

// creating all trust manager. It will accept as valid any certificate.
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};
SSLContext sslContext = SSLContext.getInstance("SSL");
// set our friendly trust manager to ssl context. we pass it to connection later
sslContext.init(null, trustAllCerts, null); 
HttpsURLConnection connection = (HttpsURLConnection) (url).openConnection();
// set all trust manager to connection
connection.setSSLSocketFactory(sslContext.getSocketFactory());
// here we say not to check host name
connection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });

after you can set headers, timeouts, e.g. as you already do for URLConnection

遥远的绿洲 2024-11-09 18:49:49

我不是 PHP 萨满,但您的代码示例中似乎有一些 PHP libcurl 绑定。您可以使用 Java libcurl 绑定在 Java 中进行相同的操作,只需稍加更改即可在此处下载

test.java 中的示例如下所示:

test cw = new test();

// Register callback write function
cg = new CurlGlue();
cg.setopt(CurlGlue.CURLOPT_WRITEFUNCTION, cw);

// Login to the bank's secure Web site, posting account number and PIN code
cg.setopt(CurlGlue.CURLOPT_URL, "https://www.santander.com.mx/SuperNetII/servlet/Login");
cg.setopt(CurlGlue.CURLOPT_SSLVERSION, iSSLVersion);
cg.setopt(CurlGlue.CURLOPT_SSL_VERIFYPEER, bInsecureMode ? 0 : 1);
cg.setopt(CurlGlue.CURLOPT_VERBOSE, bVerboseMode ? 1 : 0);
cg.setopt(CurlGlue.CURLOPT_FOLLOWLOCATION, 1);
cg.setopt(CurlGlue.CURLOPT_POST, 1);
cg.setopt(CurlGlue.CURLOPT_COOKIEJAR, "cookie.txt");
cg.setopt(CurlGlue.CURLOPT_POSTFIELDS, "pag=login&pagErr=/index.html&usuario="+account+"&clave="+pinCode+"&irAmodulo=1");
cg.perform();

不过它看起来有点粗糙。自述文件提到仅实现了简单的 API,并且可能需要手动指定一些 int 值。正确配置绑定的环境可能也需要一些努力,因为您需要确保在环境的 PATH 中找到curl 和 ssl 库。看起来 myset 脚本就是用来处理这个问题的。

I'm no PHP shaman, but it seems you got some PHP libcurl bindings in your code sample. You can do the same in Java with minor changes using the Java libcurl bindings that you can download here.

A sample from the test.java looks like this:

test cw = new test();

// Register callback write function
cg = new CurlGlue();
cg.setopt(CurlGlue.CURLOPT_WRITEFUNCTION, cw);

// Login to the bank's secure Web site, posting account number and PIN code
cg.setopt(CurlGlue.CURLOPT_URL, "https://www.santander.com.mx/SuperNetII/servlet/Login");
cg.setopt(CurlGlue.CURLOPT_SSLVERSION, iSSLVersion);
cg.setopt(CurlGlue.CURLOPT_SSL_VERIFYPEER, bInsecureMode ? 0 : 1);
cg.setopt(CurlGlue.CURLOPT_VERBOSE, bVerboseMode ? 1 : 0);
cg.setopt(CurlGlue.CURLOPT_FOLLOWLOCATION, 1);
cg.setopt(CurlGlue.CURLOPT_POST, 1);
cg.setopt(CurlGlue.CURLOPT_COOKIEJAR, "cookie.txt");
cg.setopt(CurlGlue.CURLOPT_POSTFIELDS, "pag=login&pagErr=/index.html&usuario="+account+"&clave="+pinCode+"&irAmodulo=1");
cg.perform();

It looks a bit rough though. The README mentions that only the simple API is implemented and specifying a few int values manually might be required. It might take some effort to properly configure the environment for the bindings too, as you'll need to make sure the curl and ssl libraries are found in the PATH of your environment. It looks like the myset scripts are meant to take care of this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文