【问题标题】:http request to password protected files对受密码保护的文件的 http 请求
【发布时间】:2013-09-23 13:22:11
【问题描述】:

我服务器上的 php 文件使用 htaccess 进行密码保护。如何通过我的 android 应用向这些文件发出请求?

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

【问题讨论】:

    标签: android .htaccess http


    【解决方案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 的问题。

    【讨论】:

    • 我收到未知主机异常。
    • 我的网址是cdc.acjs.co/sync/upload_profiledata.php。在尝试您的代码之前,它工作得非常好。我错过了什么吗?
    • 对不起.. 未知主机异常是由于我的互联网连接。但是,即使使用网络连接,请求也不会成功,因为返回的 json 为空。有什么想法吗?
    • 我得到一个空响应
    【解决方案2】:

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

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

    【讨论】:

    • 当我通过浏览器请求 URL 并提供您的答案时,我会收到一个确认对话框。这会妨碍我的应用访问吗?
    • 我不是 Android 开发人员,但我知道它全是 Java,您可以在打开 URL 时很好地提供身份验证信息。
    • 通过应用发送请求时出现未知主机异常。但是,当通过浏览器请求时,它可以完美运行
    • 我感觉这是由于确认对话框而发生的。有什么想法吗?
    • 我认为这不应该导致unknown host exception
    猜你喜欢
    • 2015-11-15
    • 2011-02-06
    • 2014-05-02
    • 2017-08-14
    • 1970-01-01
    • 2010-09-22
    • 2014-12-16
    • 2016-08-19
    • 2010-11-18
    相关资源
    最近更新 更多