http请求密码保护的文件

时间:2013-09-23 13:22:12

标签: android .htaccess http

我的服务器上的php文件是用htaccess密码保护的。如何通过我的Android应用程序向这些文件发出请求?

我无法通过谷歌搜索找到任何相关的答案。

2 个答案:

答案 0 :(得分:1)

在这里你可以找到答案:

Basic HTTP Authentication on Android

基本上:

HttpUriRequest request = new HttpGet(YOUR_URL); // Or HttpPost(), depends on your needs
String credentials = YOUR_USERNAME + ":" + YOUR_PASSWORD;
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Authorization", "Basic " + base64EncodedCredentials);

HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(request);
// You'll need to handle the exceptions thrown by execute()

您可以将最后一行替换为:

编辑:

你可以试试这样:

try {
HttpResponse response = httpclient.execute(request);
    //this is the login response, logged so you can see it - just use the second part of the log for anything you want to do with the data

    Log.d("Login: Response", EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
//if something went badly wrong
}

因此,您可以查看您的响应,可能问题是正在解析JSON。

答案 1 :(得分:0)

假设您的PHP文件受 HTTP Basic Authentication 保护,您可以使用以下特殊URL语法请求您的PHP文件:

http://validuser:validpassword@www.domain.com/validfile.php