2015-08-13 81 views
0

我試圖獲取需要客戶端證書的頁面的響應,我將它設置在連接參數上,並且我可以執行GET請求很好,但是當試圖通過POST發送有此錯誤:當通過POST訪問URL時出現「傳輸錯誤:401錯誤:未授權」

INFO (16:19:36,646) - basic authentication scheme selected 
INFO (16:19:36,648) - No credentials available for BASIC 'certificate'@www.nfse.erechim.rs.gov.br:8182 
INFO (16:19:36,659) - Unable to sendViaPost to url[https://www.nfse.erechim.rs.gov.br:8182/NfseService_Homolog/NfseService_Homolog] 
org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized 
java.io.IOException: Server returned HTTP response code: 401 for URL: https://www.nfse.erechim.rs.gov.br:8182/NfseService_Homolog/NfseService_Homolog 

這是我使用的代碼:

URL urlX = null; 
HttpsURLConnection connection; 
try { 
    KeyStore ks = KeyStore.getInstance("PKCS12"); 
    FileInputStream fis = new FileInputStream(Configuracoes.CAMINHO_CERTIFICADO); 
    ks.load(fis, Configuracoes.SENHA_CERTIFICADO.toCharArray()); 
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); 
    kmf.init(ks, Configuracoes.SENHA_CERTIFICADO.toCharArray()); 
    SSLContext sc = SSLContext.getInstance("TLSv1.2"); 
    sc.init(kmf.getKeyManagers(), null, null); 

    System.setProperty("https.protocols", "TLSv1.2"); 
    urlX = new URL("https://www.nfse.erechim.rs.gov.br:8182/NfseService_Homolog/NfseService_Homolog"); 
    connection = (HttpsURLConnection)urlX.openConnection(); 
    connection.setRequestMethod("POST"); 
    connection.setSSLSocketFactory(sc.getSocketFactory()); 
    connection.connect(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    String strTemp; 
    while (null != (strTemp = br.readLine())) { 
     System.out.println(strTemp); 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

我到底做錯了什麼?

回答

1

在我看來,您仍然需要憑證進行基本身份驗證。這樣做將是一個方法:

Authenticator.setDefault (new Authenticator() { 
    protected PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication ("username", "password".toCharArray()); 
    } 
}); 

但對每個請求的基礎上設置這個如果這就是你想要的東西更直接的方式(我喜歡)。看到這裏:Connecting to remote URL which requires authentication using Java

+0

謝謝,思想看起來像服務器拋出該錯誤僅僅是因爲我們必須在使用web服務之前進行註冊。 –