简体   繁体   English

使用Java输入并提交POST表单到HTTPS网站

[英]Entering and Submitting a POST Form to an HTTPS Website Using Java

What I need to do is direct Java to the HTTPS webpage, accept all the certificates, fill out the form, submit the data via POST, and then output the source of the resulting page. 我需要做的是将Java定向到HTTPS网页,接受所有证书,填写表格,通过POST提交数据,然后输出结果页面的源代码。 How would this be possible in Java(especially within the confines of an Android app)? 在Java中(特别是在Android应用程序范围内)怎么可能?

I assembled the code below from "http://alien.dowling.edu/~vassil/tutorials/javapost.php" and Kevin's answer in "http://stackoverflow.com/questions/1828775/httpclient-and-ssl", but printing the BufferedReader only prints out the form with the information filled instead of the source of the resulting page. 我从“ http://alien.dowling.edu/~vassil/tutorials/javapost.php”和凯文的答案在“ http://stackoverflow.com/questions/1828775/httpclient-and-ssl”中汇编了以下代码,但是打印BufferedReader只会打印出填充了信息的表格,而不是结果页面的源。

When submit is called, a script is run on the page using JavaScript and the URL itself does not change, but the contents of the page do change to reflect the returned results of the script. 调用Submit时,将使用JavaScript在页面上运行脚本,并且URL本身不会更改,但是页面的内容会更改以反映脚本返回的结果。 However, the current program still does not return the source of the new updated page. 但是,当前程序仍不返回新更新页面的源。 – Paradius just now –刚才的天堂

Can anyone of you show me where this code goes wrong? 谁能告诉我此代码出了错吗? Thanks in advance! 提前致谢!

import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.util.*;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class JavaPOST
{

    public static void doSubmit(String url, Map<String, String> data) throws Exception 
    {

            //SSL Certificate Acceptor
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
            SSLContext.setDefault(ctx);

            URL siteUrl = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection)siteUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setHostnameVerifier(
            new HostnameVerifier() 
            {
                @Override
                public boolean verify(String arg0, SSLSession arg1) 
                {
                    return true;
                }
            });

            DataOutputStream out = new DataOutputStream(conn.getOutputStream());

            Set keys = data.keySet();
            Iterator keyIter = keys.iterator();
            String content = "";
            for(int i=0; keyIter.hasNext(); i++) 
            {
                Object key = keyIter.next();
                if(i!=0)
                {
                    content += "&";
                }
                content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
            }           
            //System.out.println(content);
            out.writeBytes(content);
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            while((line=in.readLine())!=null) 
            {
                System.out.println(line);
            }

            System.out.println(conn.getURL());

    }

    public static void main(String[] args)
    {
        Map<String, String> data = new HashMap<String, String>();
        data.put("start_time", "103000");
        data.put("end_time", "210000");

        try
        {
            doSubmit("https://somedomain/webpage.html", data);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

class DefaultTrustManager implements X509TrustManager 
{

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

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

    }

First and foremost: don't use a make-shift, trust-everyone X509TrustManager , it is a bad idea. 首先,不要使用每个人都可以信任的X509TrustManager ,这是一个坏主意。 If you are using a self-signed certificate for the server, embed it in the app an initialize the trust manager with it. 如果您正在使用服务器的自签名证书,请将其嵌入到应用程序中,然后使用它初始化信任管理器。 There are numerous posts on how to do it properly. 有关如何正确执行操作的文章很多。

If after your POST you are redirected to a HTTP page ( not HTTPS), HttpURLConnection won't follow the redirect automatically. 如果在POST之后将您重定向到HTTP页面( 而不是 HTTPS),则HttpURLConnection将不会自动遵循重定向。 You'll have to parse the response manually (check for status code 302, etc) and GET that page using another HttpURLConnection instance. 您必须手动解析响应(检查状态代码302等),然后使用另一个HttpURLConnection实例获取该页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM