Android HttpClient .htaccess身份验证

时间:2014-11-15 23:29:04

标签: java android .htaccess authorization httpclient

很抱歉,如果这是重复的话。我试图从我的apache web服务器下载一个txt文件。它具有通过.htaccess定义的非常基本的身份验证,因此我可以在浏览器中使用简单的http://username:password@ipaddress/dir/file.txt登录。但是,此方法返回HttpClient中我的403页面的源代码。如何使用此类身份验证登录?另外,如果我可以做一些比我更安全的话,我会喜欢它。感谢。

编辑:下面的当前代码

URI url = new URI("http://username:password@ipaddress/dir/file.txt");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
    str.append(line);
}
in.close();
html = str.toString();

1 个答案:

答案 0 :(得分:0)

示例代码,您可能需要根据需要进行调整:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

StringBuilder authentication = new StringBuilder().append("username").append(":").append("password");
String result = Base64.encodeBytes(authentication.toString().getBytes());

httppost.setHeader("Authorization", "Basic " + result);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();