1

I'm trying to get the response of a page that requires client certificate, i am setting it on the connection parameters, and i can do GET requests just fine, but when trying to send via POST there's this error:

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

This is the code i am using:

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();
}

What am i doing wrong?

Mateus Viccari
  • 7,389
  • 14
  • 65
  • 101

1 Answers1

1

It seems to me as if you still require credentials for basic authentication. One way of doing so would be:

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

But there are more direct ways (which I prefer) of setting this on a per request basis if that's what you want. See here: Connecting to remote URL which requires authentication using Java

Community
  • 1
  • 1
Dennis Hunziker
  • 1,293
  • 10
  • 19
  • Thanks, thought looks like the server threw that error just because we had to make a registration before using the webservice. – Mateus Viccari Aug 17 '15 at 16:36