从android访问assembla rest API的基本身份验证
我想在我的项目中使用android环境中的AssemblaAPI。 我正在尝试执行以下基本身份验证:从android访问assembla rest API的基本身份验证,android,Android,我想在我的项目中使用android环境中的AssemblaAPI。 我正在尝试执行以下基本身份验证: String authentication = "username:password"; String encoding = Base64.encodeToString(authentication.getBytes(), 0); URL url = new URL("https://www.assembla.com/"); conn = (HttpURLC
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是否有问题,或者其他什么地方出了问题?看起来问题已经得到了回答。编码用户名密码对时,需要使用Base64.NO_WRAP标志:
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
默认情况下,Android Base64 util会在编码字符串的末尾添加一个换行符。这会使HTTP头无效并导致“错误请求”
Base64.NO_WRAP标志告诉util创建不带换行符的编码字符串,从而保持HTTP头的完整性。带有HTTP身份验证输出的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();
确认工作。实际上,我需要这个来将HTTP Basic Auth添加到Android DownloadManager请求头中。非常感谢男人,非常非常有用!