2011-03-12 57 views
5

我试图使用HTTP身份验证在线发布玩家分数,但响应始终为401(未授权),尽管我非常确定用户名和密码是正确的。我究竟做错了什么?Android HttpClient身份验证总是返回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) { 
    // 
} 

我的代码出了什么问题?

回答

12

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

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

而不是以前的

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

太好了!你可以接受你自己的问题答案,所以它显示为回答:) – 2011-03-12 19:01:29

+0

感谢您发布您的解决方案。这帮助我解决了我的问题:-) – 2011-10-25 13:22:50

+0

不幸的是,这种解决方案不适用于SSL连接。 – 2016-10-12 21:00:24

0

尝试使用:

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

请尝试提供一些解释和/或链接与您的答案解释*为什么*您的解决方案应该工作。 – codeMagic 2014-04-16 17:27:46

相关问题