2011-08-18 2 views
6

私のプロジェクトには、アンドロイド環境のassembla apisを使用したいと思います。 私は次のように基本認証を行うにしようとしています:androidからassembla rest apisにアクセスするための基本認証

String authentication = "username:password"; 
String encoding = Base64.encodeToString(authentication.getBytes(), 0);  

    URL url = new URL("https://www.assembla.com/"); 

     conn = (HttpURLConnection) url.openConnection(); 

     conn.setRequestMethod("GET"); 

     conn.setRequestProperty("Authorization", "Basic " + encoding); 
     conn.setDoOutput(true); 

     conn.connect(); 
     System.out.println(conn.getResponseCode()); 

     System.out.println(conn.getResponseMessage()); 

私は、出力400と不正な要求を取得しています。 URLが私が使用しているか間違っている何か問題がありますか?

答えて

6

質問の回答がhereのようです。ユーザ名とパスワードのペアをエンコードするときは、Base64.NO_WRAPフラグを使用する必要があります。デフォルトでは

String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP); 

は、AndroidのBase64 utilのは、エンコードされた文字列の最後に改行文字を追加します。これにより、HTTPヘッダーが無効になり、「不正な要求」が発生します。

Base64.NO_WRAPフラグは、HTTPヘッダーをそのまま維持しながら、改行文字なしでエンコードされた文字列を作成するようにutilに指示します。 HTTP認証出力と

+1

を得ました。私は実際にAndroidのDownloadManager RequestヘッダーにHTTP Basic Authを追加する必要がありました。ありがとう、たくさんの男、非常に非常に便利! –

0

RESTのAPI: - 私は結果動作を確認し

String authentication = "username:password"; 

String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP); 


HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

conn.setRequestMethod("GET"); 

conn.setDoOutput(true); 

conn.setRequestProperty ("Authorization", "Basic " + encoding); 

    conn.connect(); 

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 

wr.write(data); 

wr.flush(); 

    reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

    StringBuilder sb = new StringBuilder(); 

    String line = null; 

while((line = reader.readLine()) != null) 
         { 

    // Append server response in string 

    sb.append(line + "\n"); 


    } 

Content = sb.toString(); 
関連する問題