5

I'm trying to post the player score on-line using HTTP authentication but the response is always 401 (Unauthorized), although I'm pretty sure the username and password is correct. What am I doing wrong?

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) {
    //
}

What's wrong with my code?

2 Answers 2

12

I solved the problem. I'm using

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

instead of the previous

new AuthScope("http://myurl.com/score.php", 80) // error
Sign up to request clarification or add additional context in comments.

3 Comments

Great! You can accept your own answer to the question so it shows up as answered :)
Thanks for posting your solution. This helped me solve my problem :-)
Unfortunately this solution doesn't work for SSL connections.
0

Try using:

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

1 Comment

Please try to provide some explanation and/or links with your answers to explain why your solution should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.