Java从HTTPS html表单下载文件

时间:2014-04-01 14:50:40

标签: java httpurlconnection

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

我有一个很棒的程序,我不能使用Apache Commons HttpClient,因为除了excel和pdfs文件之外我无法从我的工作中下载任何东西。得到Eclipse非常困难。

因此,我正在使用HttpURLConnection(我也尝试过HttpsURLConnection),但这种方式我甚至无法连接到网站,因此将参数发送到表单并下载文件是不可能的。

拜托,有人可以帮助我吗?

谢谢和问候。

1 个答案:

答案 0 :(得分:0)

您应该使用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;
    }