【问题标题】:Android HttpClient authentication always returns 401 codeAndroid HttpClient 身份验证总是返回 401 代码
【发布时间】:2011-03-12 17:03:36
【问题描述】:

我正在尝试使用 HTTP 身份验证在线发布玩家得分,但响应始终为 401(未经授权),尽管我很确定用户名和密码是正确的。我做错了什么?

DefaultHttpClient client = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials("user", "passsword");
client.getCredentialsProvider().setCredentials(new AuthScope("http://myurl.com/score.php", 80), creds);

try {
    HttpPost post = new HttpPost("http://myurl.com/score.php");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);   
    nameValuePairs.add(new BasicNameValuePair("score", points));
    nameValuePairs.add(new BasicNameValuePair("name", name));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = client.execute(post);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        throw new Exception();
    }

} catch (UnsupportedEncodingException e) {
    //
} catch (IOException e) {
    //
} catch (Exception e) {
    //
}

我的代码有什么问题?

【问题讨论】:

    标签: android authentication post httpclient


    【解决方案1】:

    我解决了这个问题。我正在使用

    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT) // works
    

    而不是以前的

    new AuthScope("http://myurl.com/score.php", 80) // error
    

    【讨论】:

    • 太棒了!您可以接受自己对问题的回答,使其显示为已回答:)
    • 感谢您发布您的解决方案。这帮助我解决了我的问题:-)
    • 很遗憾,此解决方案不适用于 SSL 连接。
    【解决方案2】:

    尝试使用:

    new AuthScope("myurl.com", 80);
    

    【讨论】:

    • 请尝试提供一些解释和/或您的答案的链接,以解释为什么您的解决方案应该有效。
    猜你喜欢
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2016-10-02
    • 2012-12-14
    相关资源
    最近更新 更多