2014-04-01 73 views
0

我必須從網站下載文件。這是一個普通的html表單,我通常從html表單下載幾個文件。但是,這是一個只允許通過HTTPS訪問的網站。Java從HTTPS html格式下載文件

我有一個很棒的程序,我不能使用Apache Commons HttpClient,因爲我無法從excel和pdfs文件以外的任何地方下載任何內容。得到Eclipse非常困難。因此,我使用HttpURLConnection(我也試過HttpsURLConnection),但是這種方式我甚至無法連接到站點,所以發送參數到窗體並下載文件是不可能的。

請問有人可以幫我嗎?

感謝和問候。

回答

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; 
    } 
+0

謝謝你的迴應。您通過的鏈接不能解釋如何進行身份驗證。你能讓我知道正確的嗎? –

+0

我希望它有幫助:連接總是返回下面的錯誤:'連接超時:連接' –

+0

編輯,但'連接超時'似乎沒有連接到它的加密,如果你有一個身份驗證問題會寫一些類似'無法驗證..',也許有鏈接或代碼中的其他東西。 – omriman12