【问题标题】:Java download a file from HTTPS html formJava 从 HTTPS html 表单下载文件
【发布时间】:2014-04-01 14:50:40
【问题描述】:

我必须从网站下载文件。这是一个普通的html表单,我通常从html表单下载几个文件。但是这个是在一个只允许通过 HTTPS 访问的站点中。

我有一个很棒的程序,但我不能使用 Apache Commons HttpClient,因为除了 excel 和 pdfs 文件之外,我无法从我的工作中下载任何内容。 Eclipse 太难搞定了。

因此,我正在使用 HttpURLConnection(我也尝试过 HttpsURLConnection),但是这样我什至无法连接到站点,因此无法将参数发送到表单并下载文件。

请问有人可以帮我吗?

感谢和问候。

【问题讨论】:

    标签: java httpurlconnection


    【解决方案1】:

    那么您应该使用HttpsURLConnection 并验证请求。

    看这里:Tring to connect using HTTPS: Server redirected too many times

    编辑

    应该是这样的代码:

    private void SendRequest(string url, string data){
    
        Stream dataStream = null;
        WebResponse response = null;
    
        try
        {
            string requestXml = Sendingxml.ToString();
    
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
    
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
    
            string formParams = string.Format("data={0}",  data);
    
            byte[] byteArray = Encoding.UTF8.GetBytes(formParams);
            request.ContentType = "application/x-www-form-urlencoded";
            encoding='utf-8'";
            request.ContentLength = byteArray.Length;
    
            dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
    
            response = request.GetResponse();
            dataStream = response.GetResponseStream();
    
            string responseFromServer = "";
            using (StreamReader reader = new StreamReader(dataStream))
            {
                responseFromServer = reader.ReadToEnd();
            }
    
            return responseFromServer;
        }
        catch (Exception e)
        {
            throw new CommunicationFailure();
        }
        finally
        {
            if (dataStream != null)
                dataStream.Close();
            if (response != null)
                response.Close();
        }
    }
    
    
    private bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    

    【讨论】:

    • 感谢您的回复。您传递的链接没有说明如何进行身份验证。你能告诉我正确的吗?
    • 我希望它有所帮助:连接总是返回以下错误:Connection timed out: connect
    • 已编辑,但“连接超时”似乎与它已加密的事实无关,如果您在身份验证方面遇到问题,它可能会写出类似“身份验证失败..”之类的内容带有链接的内容或代码中的其他内容。
    • 再次感谢您。你写的都是C#,我用的是Java。我不知道如何翻译它。我认为您对它的工作方式是正确的,并且可能与身份验证无关。我真的不知道。
    猜你喜欢
    • 2012-08-24
    • 2014-07-20
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多