Android HttpClient身份验证始终返回401代码

时间:2011-03-12 17:03:36

标签: android authentication post httpclient

我正在尝试使用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) {
    //
}

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:12)

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

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

而不是之前的

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

答案 1 :(得分:0)

尝试使用:

new AuthScope("myurl.com", 80);
相关问题