2016-04-19 22 views
1

HTTPSページ呼び出しがうまく機能していて、HTTP基本認証がHTTPS接続で実行されている基本認証を取得できないように正常に動作しています。Basic Auth over HTTPS Java

コード例を添付しますが、動作しません。私は403を取得し続けます。私はユーザー名とパスワードを確認して、FirefoxからRESTClinetアドオンでテストすると成功しました。

助けがあれば助かります。ありがとう。

private static void getAPITest() throws MalformedURLException, IOException 
{   
    try { 


    System.setProperty("javax.net.ssl.trustStore","/home/USER/CERTS/myTrustStore"); 
    System.setProperty("javax.net.ssl.trustStorePassword", "PASSWORD"); 


    Authenticator myAuth = new Authenticator() 
     { 
      @Override 
      protected PasswordAuthentication getPasswordAuthentication() 
      { 
       return new PasswordAuthentication("USERNAME", "PASSWORD".toCharArray()); 
      } 
     }; 

     Authenticator.setDefault(myAuth); 


     String httpsURL = "https://someurlandapi.com"; 
     URL myurl = new URL(httpsURL); 
     HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection(); 
     //con.setRequestProperty("Authorization", "Basic " + authString); 
     con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
     con.setRequestProperty("Accept", "application/json"); 
     con.setRequestMethod("POST");    

     InputStream ins = con.getInputStream(); 
     InputStreamReader isr = new InputStreamReader(ins); 
     BufferedReader in = new BufferedReader(isr); 

     String inputLine; 

     while ((inputLine = in.readLine()) != null) 
     { 
      System.out.println(inputLine); 
     } 

     ins.close(); 
     in.close(); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

答えて

0

私はPasswordAuthenticationが望んでいるとは思わない。しかし基本的な認証は本当にあなた自身を扱うのは簡単です。 Java8の場合は、単純にBase64.getEncoder()。encodeToString(( "USERNAME" + ":" + "PASSWORD")getBytes())です。

+0

はい、私はまだ403をその同じ問題を試してみました。 – DevilCode

0

それが基本的な前にスペースを持っていないが判明:

con.setRequestProperty("Authorization", "Basic " + authStringEnc); 

、それが必要:

conn.setRequestProperty("User-Agent", "Mozilla/5"); 

これを行う人のための簡単なメモをあなたがあなた自身のトラストストアを作成している場合sites/urls SSL証明書チェーンを追加する必要があります。 firefoxでは、パドロック>詳細情報>セキュリティ>証明書をクリックすることができます。そこから、あなたはそれが、その後のkeytoolを使用してトラストストアに追加チェーンと証明書のエクスポートを強調表示することができます。

keytool -import -file websitecertificate.pem -alias websitecert -keystore myTrustStore