12rad
12rad

Reputation: 849

HttpClient authentication -

I am trying to emulate this behavior in java

curl -u usrname:password http://somewebsite.com/docs/DOC-2264

I am not sure if the auth is NTLM or Basic. I login to the website giving a username and passoword. It's a form post. Using the curl command above I am able to login and get the content.

To do this in java I did:

    try {
        URL url = new URL("http://somewebsite.com/docs/DOC-2264");
        String authStr ="username:password";
        String encodedAuthStr = Base64.encodeBytes(authStr.getBytes());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        onnection.setRequestProperty("Authorization", "Basic" + encodedAuthStr);

        InputStream content = (InputStream)connection.getInputStream();
        BufferedReader in   = 
            new BufferedReader (new InputStreamReader (content));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }           


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

But I only get the login page. Not the actual content. What am i doing wrong?

Upvotes: 1

Views: 1571

Answers (2)

ataylor
ataylor

Reputation: 66059

  1. You can see the exact header curl is sending by adding the -v (verbose) option.
  2. The Authorization header needs the authentication type before the base64 encoded username/password. It should look something like this: Authorization: Basic dXNybmFtZTpwYXNzd29yZA==

Upvotes: 1

Rocky Pulley
Rocky Pulley

Reputation: 23301

Maybe curl just does the equivalent of this:

URL url = new URL("http://username:[email protected]/docs/DOC-2264");

Upvotes: 0

Related Questions